/**
  * Checks that the application manifest is properly configured.
  *
  * <p>A proper configuration means:
  *
  * <ol>
  *   <li>It creates a custom permission called {@code PACKAGE_NAME.permission.C2D_MESSAGE}.
  *   <li>It defines at least one {@link BroadcastReceiver} with category {@code PACKAGE_NAME}.
  *   <li>The {@link BroadcastReceiver}(s) uses the {@value
  *       org.wso2.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS} permission.
  *   <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents ({@value
  *       org.wso2.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} and {@value
  *       org.wso2.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}).
  * </ol>
  *
  * ...where {@code PACKAGE_NAME} is the application package.
  *
  * <p>This method should be used during development time to verify that the manifest is properly
  * set up, but it doesn't need to be called once the application is deployed to the users'
  * devices.
  *
  * @param context application context.
  * @throws IllegalStateException if any of the conditions above is not met.
  */
 public static void checkManifest(Context context) {
   PackageManager packageManager = context.getPackageManager();
   String packageName = context.getPackageName();
   String permissionName = packageName + ".permission.C2D_MESSAGE";
   // check permission
   try {
     packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS);
   } catch (NameNotFoundException e) {
     throw new IllegalStateException("Application does not define permission " + permissionName);
   }
   // check receivers
   PackageInfo receiversInfo;
   try {
     receiversInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_RECEIVERS);
   } catch (NameNotFoundException e) {
     throw new IllegalStateException("Could not get receivers for package " + packageName);
   }
   ActivityInfo[] receivers = receiversInfo.receivers;
   if (receivers == null || receivers.length == 0) {
     throw new IllegalStateException("No receiver for package " + packageName);
   }
   if (Log.isLoggable(TAG, Log.VERBOSE)) {
     Log.v(TAG, "number of receivers for " + packageName + ": " + receivers.length);
   }
   Set<String> allowedReceivers = new HashSet<String>();
   for (ActivityInfo receiver : receivers) {
     if (GCMConstants.PERMISSION_GCM_INTENTS.equals(receiver.permission)) {
       allowedReceivers.add(receiver.name);
     }
   }
   if (allowedReceivers.isEmpty()) {
     throw new IllegalStateException(
         "No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS);
   }
   checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
   checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE);
 }
  @Override
  public int installPackage(String filepath, int flags) throws RemoteException {
    // install plugin
    String apkfile = null;
    try {
      PackageManager pm = mContext.getPackageManager();
      PackageInfo info = pm.getPackageArchiveInfo(filepath, 0);
      if (info == null) {
        return PackageManagerCompat.INSTALL_FAILED_INVALID_APK;
      }

      apkfile = PluginDirHelper.getPluginApkFile(mContext, info.packageName);

      if ((flags & PackageManagerCompat.INSTALL_REPLACE_EXISTING) != 0) {
        forceStopPackage(info.packageName);
        if (mPluginCache.containsKey(info.packageName)) {
          deleteApplicationCacheFiles(info.packageName, null);
        }
        new File(apkfile).delete();
        Utils.copyFile(filepath, apkfile);
        PluginPackageParser parser = new PluginPackageParser(mContext, new File(apkfile));
        parser.collectCertificates(0);
        PackageInfo pkgInfo =
            parser.getPackageInfo(PackageManager.GET_PERMISSIONS | PackageManager.GET_SIGNATURES);
        if (pkgInfo != null
            && pkgInfo.requestedPermissions != null
            && pkgInfo.requestedPermissions.length > 0) {
          for (String requestedPermission : pkgInfo.requestedPermissions) {
            boolean b = false;
            try {
              b = pm.getPermissionInfo(requestedPermission, 0) != null;
            } catch (NameNotFoundException e) {
            }
            if (!mHostRequestedPermission.contains(requestedPermission) && b) {
              Log.e(TAG, "No Permission %s", requestedPermission);
              new File(apkfile).delete();
              return PluginManager.INSTALL_FAILED_NO_REQUESTEDPERMISSION;
            }
          }
        }
        saveSignatures(pkgInfo);
        //                if (pkgInfo.reqFeatures != null && pkgInfo.reqFeatures.length > 0) {
        //                    for (FeatureInfo reqFeature : pkgInfo.reqFeatures) {
        //                        Log.e(TAG, "reqFeature name=%s,flags=%s,glesVersion=%s",
        // reqFeature.name, reqFeature.flags, reqFeature.getGlEsVersion());
        //                    }
        //                }
        copyNativeLibs(mContext, apkfile, parser.getApplicationInfo(0));
        dexOpt(mContext, apkfile, parser);
        mPluginCache.put(parser.getPackageName(), parser);
        mActivityManagerService.onPkgInstalled(mPluginCache, parser, parser.getPackageName());
        sendInstalledBroadcast(info.packageName);
        return PackageManagerCompat.INSTALL_SUCCEEDED;
      } else {
        if (mPluginCache.containsKey(info.packageName)) {
          return PackageManagerCompat.INSTALL_FAILED_ALREADY_EXISTS;
        } else {
          forceStopPackage(info.packageName);
          new File(apkfile).delete();
          Utils.copyFile(filepath, apkfile);
          PluginPackageParser parser = new PluginPackageParser(mContext, new File(apkfile));
          parser.collectCertificates(0);
          PackageInfo pkgInfo =
              parser.getPackageInfo(PackageManager.GET_PERMISSIONS | PackageManager.GET_SIGNATURES);
          if (pkgInfo != null
              && pkgInfo.requestedPermissions != null
              && pkgInfo.requestedPermissions.length > 0) {
            for (String requestedPermission : pkgInfo.requestedPermissions) {
              boolean b = false;
              try {
                b = pm.getPermissionInfo(requestedPermission, 0) != null;
              } catch (NameNotFoundException e) {
              }
              if (!mHostRequestedPermission.contains(requestedPermission) && b) {
                Log.e(TAG, "No Permission %s", requestedPermission);
                new File(apkfile).delete();
                return PluginManager.INSTALL_FAILED_NO_REQUESTEDPERMISSION;
              }
            }
          }
          saveSignatures(pkgInfo);
          //                    if (pkgInfo.reqFeatures != null && pkgInfo.reqFeatures.length > 0) {
          //                        for (FeatureInfo reqFeature : pkgInfo.reqFeatures) {
          //                            Log.e(TAG, "reqFeature name=%s,flags=%s,glesVersion=%s",
          // reqFeature.name, reqFeature.flags, reqFeature.getGlEsVersion());
          //                        }
          //                    }

          copyNativeLibs(mContext, apkfile, parser.getApplicationInfo(0));
          dexOpt(mContext, apkfile, parser);
          mPluginCache.put(parser.getPackageName(), parser);
          mActivityManagerService.onPkgInstalled(mPluginCache, parser, parser.getPackageName());
          sendInstalledBroadcast(info.packageName);
          return PackageManagerCompat.INSTALL_SUCCEEDED;
        }
      }
    } catch (Exception e) {
      if (apkfile != null) {
        new File(apkfile).delete();
      }
      handleException(e);
      return PackageManagerCompat.INSTALL_FAILED_INTERNAL_ERROR;
    }
  }
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main3);
    mPm = getPackageManager();
    Intent i = getIntent();
    String title = i.getStringExtra("title");
    final String PackageName = title.substring(8);

    ExpandableListView list = (ExpandableListView) findViewById(R.id.permissionList);
    mGroupData = new ArrayList<Map<String, String>>();
    mChildData = new ArrayList<List<Map<String, String>>>();
    String permissionName;
    String applicationLabel;
    String packageName;
    PackageInfo pi = null;
    ApplicationInfo ai = null;
    applicationLabel = PackageName;
    int packageVersionCode;
    String packageVersionName;
    String AppName;
    Drawable icon;
    long lastUpdate;
    int system;
    int install;

    try {
      pi = mPm.getPackageInfo(PackageName, PackageManager.GET_META_DATA);

      try {
        icon = mPm.getApplicationIcon(PackageName); // ///icon  빼기

      } catch (PackageManager.NameNotFoundException e) {
        icon = mPm.getDefaultActivityIcon();
      }

      ImageView imageView = (ImageView) findViewById(android.R.id.icon);
      imageView.setImageDrawable(icon);

      AppName = pi.packageName;
      packageVersionCode = pi.versionCode;
      packageVersionName = pi.versionName;
      Log.v("XXXX7", "name:     " + packageVersionName);

      ai = mPm.getApplicationInfo(PackageName, PackageManager.GET_META_DATA); // //라벨 빼오기
      String labelName = mPm.getApplicationLabel(ai).toString();

      ((TextView) findViewById(R.id.curAppName)).setText(labelName); // Appname layout 연결
      ((TextView) findViewById(R.id.packagea)).setText(AppName); // Appname layout 연결
      ((TextView) findViewById(R.id.curAppversion))
          .setText(packageVersionCode + " / " + packageVersionName);

    } catch (Exception ex) {
      packageVersionCode = 0;
      packageVersionName = "n/a";
      // Log.e("PM", "Error fetching app version");
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////

    manageButton = (ImageButton) findViewById(R.id.application_detail_manage_button);
    manageButton.setImageResource(R.drawable.ic_menu_manage);
    manageButton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            if (Build.VERSION.SDK_INT >= 9) {
              try {
                Intent i = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
                i.addCategory(Intent.CATEGORY_DEFAULT);
                i.setData(Uri.parse("package:" + PackageName));
                startActivity(i);
              } catch (ActivityNotFoundException anfe) {
                Intent i = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
                i.addCategory(Intent.CATEGORY_DEFAULT);
                startActivity(i);
              }
            } else {
              Toast.makeText(
                      MarketPlay.this,
                      context.getText(R.string.application_detail_manager_unavailable),
                      Toast.LENGTH_LONG)
                  .show();
            }
          }
        });

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    try {
      pi = mPm.getPackageInfo(PackageName, PackageManager.GET_PERMISSIONS);

    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }

    mChildData.clear();
    mGroupData.clear();

    //        int count = 0;
    //        try {
    //            for (String key : pi.requestedPermissions) {
    //                if (key.startsWith("android.permission.")) count++;
    //            }
    //            curGroupMap.put(NAME, applicationLabel + "(" + count + ")");
    //            Log.v("XXXX7", "count :     " + count);
    //        } catch (NullPointerException e) {
    //            curGroupMap.put(NAME, applicationLabel + "(" + 0 + ")");
    //            Log.v("XXXX7", "///count :     " + count);
    //        }
    //        curGroupMap.put(DESCRIPTION, packageVersionName);
    //        Log.v("XXXX7", "Description  :     " + packageVersionName);
    //        curGroupMap.put(PACKAGENAME, PackageName);
    //        Log.v("XXXX7", "packageName  :     " + PackageName);
    //
    //        mGroupData.add(curGroupMap);

    Log.v("1", "" + mChildData);

    Log.v("2", "" + mChildData);
    try {
      Log.v("3", "" + mChildData);
      if (pi.requestedPermissions != null) {
        for (String key : pi.requestedPermissions) {
          try {
            if (!(key.startsWith("android.permission."))) continue;
            Log.d("BBB", key);
            PermissionInfo pinfo = mPm.getPermissionInfo(key, PackageManager.GET_META_DATA);
            Map<String, String> curGroupMap = new HashMap<String, String>();
            Map<String, String> curChildMap = new HashMap<String, String>();
            List<Map<String, String>> children = new ArrayList<Map<String, String>>();
            CharSequence label = pinfo.loadLabel(mPm);
            CharSequence desc = pinfo.loadDescription(mPm);

            curGroupMap.put(NAME, (label == null) ? pinfo.name : label.toString());
            Log.d("AAA", label.toString());
            curGroupMap.put(SECURITYLEVEL, String.valueOf(pinfo.protectionLevel));
            curChildMap.put(PERMISSION, key);
            curChildMap.put(DESCRIPTION, (desc == null) ? "" : desc.toString());
            curChildMap.put(SECURITYLEVEL, String.valueOf(pinfo.protectionLevel));
            children.add(curChildMap);

            mGroupData.add(curGroupMap);
            Log.d("CCC", "" + mGroupData);
            mChildData.add(children);
            Log.d("DDD", "" + mChildData);

          } catch (PackageManager.NameNotFoundException e) {
            Log.i(TAG, "Ignoring unknown permission ");
            continue;
          }
        }
      } else {
        ((TextView) findViewById(R.id.iff)).setText(" App 의 요구 권한 이 없습니다 ^^  ");

        //                mGroupData.add(curGroupMap);
        //                mChildData.add(children);
      }
    } catch (NullPointerException e) {
      Log.i(TAG, "Ignoring unknown permission ");
    }

    //        SimpleAdapter adapter = new SimpleAdapter(this, children,
    // R.layout.permission_list_item, new String[]{"", "Name", "Description"}, new
    // int[]{R.id.listviewpermissiontext, R.id.text1, R.id.text2});
    //        if (pi.requestedPermissions != null) {
    //            permissionList = (ListView) findViewById(R.id.permissionList);
    //            permissionList.setAdapter(adapter);
    //        } else {
    //            ((TextView) findViewById(R.id.iff)).setText(" App 의 요구 권한 이 없습니다 ^^  ");
    //        }

    PermissionAdapter mAdapter =
        new PermissionAdapter(
            MarketPlay.this,
            mGroupData,
            R.layout.marketplay_item,
            new String[] {NAME},
            new int[] {R.id.text1},
            mChildData,
            R.layout.marketplay_item_child,
            new String[] {DESCRIPTION, PERMISSION},
            new int[] {R.id.text1, R.id.text2});

    list.setAdapter(mAdapter);

    Log.v("BBB", "" + mChildData);

    // permissionList = (ListView)findViewById(R.id.permissionL);
    // permissionList.setAdapter(adapter);    ///권한들 .. layout

  }