package com.sheep.jiuyan.samllsheep.utils;

import android.app.ActivityManager;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;

import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.SheepApp;

import java.io.File;
import java.util.List;

/**
 * Created by kemllor on 2017/12/14.
 */

public class PackageUtil {

    public static String getLauncherTopApp(Context context) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> appTasks = activityManager.getRunningTasks(1);
            if (null != appTasks && !appTasks.isEmpty()) {
                return appTasks.get(0).topActivity.getPackageName();
            }
        } else {
            long endTime = System.currentTimeMillis();
            long beginTime = endTime - 10000;
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            String result = "";
            UsageEvents.Event event = new UsageEvents.Event();
            UsageEvents usageEvents = mUsageStatsManager.queryEvents(beginTime, endTime);
            while (usageEvents.hasNextEvent()) {
                usageEvents.getNextEvent(event);
                if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                    result = event.getPackageName();
                }
            }
            if (!android.text.TextUtils.isEmpty(result)) {
                return result;
            }
        }
        return "";
    }


    /*
    * 判断是否安装
    * check the app is installed
    */
    public static boolean isAppInstalled(Context context, String packageName) {
        PackageInfo packageInfo;
        try {
            PackageManager  manager=context.getPackageManager();
            if(manager==null){
                return false;

            }else {
                packageInfo = manager.getPackageInfo(packageName, 0);
            }
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
        }
        if (packageInfo == null) {
            //System.out.println("没有安装");
            return false;
        } else {
            //System.out.println("已经安装");
            return true;
        }
    }


    public static  void  install(Context context, String path){

        File file = new File(path);

        G.showInstallToast(context, file);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //判读版本是否在7.0以上
                Uri apkUri = FileProvider.getUriForFile(context, SheepApp.getInstance().getPackageName() + ".fileprovider", file);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
        }catch (Exception e){
            e.printStackTrace();
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);

    }



    /*
    * 安装
    * install app
    */
    public static void installApk(final Context context,final String path) {
        UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_INSTALL_APP);
        install(context, path);
//        if (Build.VERSION.SDK_INT >= 26) {//判读版本是否在8.0以上
//
//
//            Acp.getInstance(context).request(new AcpOptions.Builder()
//                            .setPermissions(Manifest.permission.REQUEST_INSTALL_PACKAGES
//                            )
//                            .build(),
//                    new AcpListener() {
//                        @Override
//                        public void onGranted() {
//                            install(context, path);
//                        }
//
//                        @Override
//                        public void onDenied(List<String> permissions) {
//                            Toast.makeText(context, "亲！权限拒绝将无法安装游戏，进行赚钱...", Toast.LENGTH_LONG).show();
//
//                        }
//                    });
//
//        }else{
//
//            install(context, path);
//        }



    }
    /*
     * 启动
     * install app
     */
    public static void startApp(Context context, String packagename) {

        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = context.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = null;
        try {
            resolveinfo = resolveinfoList.iterator().next();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (resolveinfo != null) {
            // packagename = 参数packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);
            intent.setComponent(cn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
        UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_START_APP);
    }

    //判断程序是否前台运行；
    public static boolean isAppOnForeground(Context context) {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    /**
     * 通过包名、路径判断是否下载过
     */
    public static String isExistsFile(String packName, String downloadUrl){
        ClassFileHelper.getInstance().createSDDirection();
        File mApkPath = new File(ClassFileHelper.DIR, packName + downloadUrl.hashCode() + ClassFileHelper.FILE_SUFFIX);
        if (!mApkPath.exists()) {
            return null;
        }else{
            return mApkPath.getAbsolutePath();
        }
    }
}
