package com.sheep.gamegroup.usage;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppOpsManager;
import android.app.Service;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;

import com.kfzs.duanduan.utils.ApkUtils;
import com.sheep.gamegroup.model.entity.AppRecord;
import com.sheep.gamegroup.model.entity.AppUsage;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.UserAssets;
import com.sheep.gamegroup.model.util.AutoTaskListUtil;
import com.sheep.gamegroup.util.ActivityManager;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import static android.content.Context.USAGE_STATS_SERVICE;

/**
 * Created by realicing on 2018/6/27.
 * realicing@sina.com
 */
public class AppUsageManager {

    private static AppUsageManager instance = new AppUsageManager();

    private AppUsageManager(){
    }
    public static AppUsageManager getInstance(){
        if (instance == null){
            instance = new AppUsageManager();
        }
        return instance;
    }

    //记录前台app运行时长
    public void recordCurrentAppUsage() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//android 7.0以上不支持
//            return;
//        }
//        List<AndroidAppProcess> processes = AndroidProcesses.getRunningForegroundApps(SheepApp.getInstance());
//        AndroidAppProcess androidAppProcess = ListUtil.getLast(processes);
//        if (androidAppProcess != null) {
//            String packageName = androidAppProcess.name;
//            String appName = null;
//            try {
//                PackageInfo packageInfo = androidAppProcess.getPackageInfo(SheepApp.getInstance(), 0);
//                appName = packageInfo.applicationInfo.loadLabel(SheepApp.getInstance().getPackageManager()).toString();
//
//                LogUtil.println("getAppTime", appName, packageName);
//            } catch (PackageManager.NameNotFoundException e) {
//                e.printStackTrace();
//            }

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {//android 5.0以上不支持
            return;
        }
        android.app.ActivityManager.RunningAppProcessInfo process = getAppProcessInfoInForeground();
        if (process != null) {
//                LogUtil.println("getRunningAppProcesses", process.processName, process.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND);
            String packageName = process.processName;//没有packageName字段，可能会出问题
            String appName = null;
            PackageInfo packageInfo = ApkUtils.getPackageInfo(SheepApp.getInstance().getPackageName());
            if (packageInfo != null)
                appName = packageInfo.applicationInfo.loadLabel(SheepApp.getInstance().getPackageManager()).toString();

            LogUtil.println("getAppTime", appName, packageName);

            if (AutoTaskListUtil.getInstance().isLastAppRecord(packageName)) {//仍然是之前的app
                return;
            }

            long curTime = System.currentTimeMillis();
            AppRecord appRecord = new AppRecord();
            appRecord.setPackageName(packageName);
            if (appName != null)
                appRecord.setTag(appName);

            AppRecord lastAppRecord = AutoTaskListUtil.getInstance().getLastAppRecord();
            long lastTime = AutoTaskListUtil.getInstance().getLastTime();
            if (lastAppRecord != null && lastTime != 0)
                lastAppRecord.setTime(lastAppRecord.getTime() + curTime - lastTime);
            if (lastAppRecord != null && AutoTaskListUtil.getInstance().hasTask(lastAppRecord)) {
                MyDbManager.getInstance().saveOrUpdate(lastAppRecord);
                LogUtil.println("AppUsageManager", "recordCurrentAppUsage", "MyDbManager", "saveOrUpdate", "lastAppRecord", lastAppRecord.getPackageName(), lastAppRecord.getTime());
            }

            AutoTaskListUtil.getInstance().setLastTime(curTime);
            AutoTaskListUtil.getInstance().setLastAppRecord(appRecord);
        }
    }

    private android.app.ActivityManager.RunningAppProcessInfo getAppProcessInfoInForeground() {
        android.app.ActivityManager manager = (android.app.ActivityManager) SheepApp.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        List<android.app.ActivityManager.RunningAppProcessInfo> processList = manager == null ? null : manager.getRunningAppProcesses();
        if(!ListUtil.isEmpty(processList)){
            for (android.app.ActivityManager.RunningAppProcessInfo item : processList) {
                if(item != null && item.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
                    return item;
                }
            }
        }
        return null;
    }

    /**
     * 需要开启查看应用使用情况的权限
     *
     * @return
     */
    @SuppressLint("NewApi")
    public  boolean needOpenLookAppUsageStatsPermisson(boolean isSaveData){
        if(android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){   // 如果大于等于5.1 再做判断
            long time = System.currentTimeMillis();
            UsageStatsManager usageStatsManager=(UsageStatsManager)SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);
            List<UsageStats> queryUsageStats = usageStatsManager != null ? usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, time) : null;
            boolean isEmpty = ListUtil.isEmpty(queryUsageStats);
            if(!isEmpty && isSaveData){
                List<AppUsage> appUsageList = ListUtil.emptyList();
                for (UsageStats queryUsageStat : queryUsageStats) {
                    appUsageList.add(AppUsage.getInstance(queryUsageStat));
                }
                MyDbManager.getInstance().saveOrUpdate(appUsageList);//保存或者更新AppUsage,以便之后用来显示时间
            }
            AppOpsManager appOps = (AppOpsManager) SheepApp.getInstance().getSystemService(Context.APP_OPS_SERVICE);
            int mode = -1;
            if(appOps != null) {
                mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), SheepApp.getInstance().getPackageName());
            }
            boolean granted = mode == AppOpsManager.MODE_ALLOWED;
            return isEmpty || !granted;
        } else{
            return false;
        }
    }

    /**
     * 尝试打开权限对话框 5.1及以上使用
     * @param isSaveData 是否保存AppUsage数据,因为AppUsage通过系统获取的数据转化而来，而且，不切换应用时不会改变，而要实时显示时间就必须缓冲数据
     */
    public void tryOpenLookAppUsageStatsPermisson(boolean isSaveData) {
        if (!needOpenLookAppUsageStatsPermisson(isSaveData)) {//不需要开启
            return;
        }
        if(AutoTaskListUtil.getInstance().isShowing()){//对话框仍在显示,就不显示 打开权限功能的对话框
            return;
        }
        LogUtil.println("tryOpenLookAppUsageStatsPermisson", "start");
        AutoTaskListUtil.getInstance().clearAlertDialog();
        if(!AutoTaskListUtil.getInstance().isEmpty()){
            LogUtil.println("tryOpenLookAppUsageStatsPermisson", "notEmpty");
            showAccessibilityDialog();
        } else {
            LogUtil.println("tryOpenLookAppUsageStatsPermisson","else");
        }
        LogUtil.println("tryOpenLookAppUsageStatsPermisson","end");
    }
    public void showAccessibilityDialog() {
        AlertDialog tipToOpernAccessibilityDialog = ViewUtil.showMsgDialog(SheepApp.getInstance(), new DialogConfig().setTitle("温馨提示！")
                .setMsg("亲！系统检测到您需要手动开启小绵羊查看应用情况的权限才能继续任务！")
                .setBtnLeftText("去开启").setBtnLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        openLookAppUsageStatsPermisson();
                    }
                }));
        tipToOpernAccessibilityDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                AutoTaskListUtil.getInstance().clearAlertDialog();
            }
        });
        AutoTaskListUtil.getInstance().setTipToOpernAccessibilityDialog(tipToOpernAccessibilityDialog);
    }
    public void openLookAppUsageStatsPermisson(){
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            try {
                Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ActivityManager.getInstance().currentActivity().startActivity(intent);
            } catch (Exception e) {
                G.showToast("请自行在设置中的“有权查看使用情况的应用”界面中开启小绵羊查看应用使用情况的权限");
                e.printStackTrace();
            }
        }
    }
    private HashMap<String, Long> totalTimeMap = new HashMap<>();
    private HashMap<String, Long> timeMap = new HashMap<>();
    public long getTotalTimeInForeground(String packageName) {
        AppUsage appUsage = new AppUsage();
        appUsage.setPackageName(packageName);
        return getTotalTimeInForeground(appUsage);
    }
    @SuppressLint("NewApi")
    public long getTotalTimeInForeground(AppUsage appUsage) {
        String packageName = appUsage.getPackageName();
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);//usagestats
            long time = System.currentTimeMillis();
            if(mUsageStatsManager != null) {
                List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, AutoTaskListUtil.getInstance().getReceiveTaskTime(), time);

                if (usageStatsList != null && !usageStatsList.isEmpty()) {
                    if(packageName == null){//为空时需要获取前台的packageName
                        TreeMap<Long,UsageStats> mySortedMap = new TreeMap<>();
                        for (UsageStats item : usageStatsList) {
                            mySortedMap.put(item.getLastTimeUsed(),item);
                        }

                        UsageStats usageStats = mySortedMap.get(mySortedMap.lastKey());

                        packageName = usageStats.getPackageName();
                        appUsage.setPackageName(packageName);
                        long totalTime = usageStats.getTotalTimeInForeground();
                        long saveTotalTime = MyDbManager.getInstance().getAppUsageTime(packageName);
                        if((saveTotalTime <= 0 || saveTotalTime > totalTime) && totalTime > 0){
                            appUsage.setTotalTimeInForeground(totalTime);
                            MyDbManager.getInstance().saveOrUpdate(appUsage);
                        }
                        if (totalTimeMap.containsKey(packageName) && totalTimeMap.get(packageName) == totalTime) {
                            totalTime += time - timeMap.get(packageName);
                        } else {
                            totalTimeMap.put(packageName, totalTime);
                            timeMap.put(packageName, time);
                        }
                        return Math.max(0, totalTime - saveTotalTime);
                    } else {//小绵羊在前台时调用
                        for (UsageStats usageStats : usageStatsList) {
                            if (usageStats != null && TextUtils.equals(packageName, usageStats.getPackageName())) {
                                long saveTotalTime = MyDbManager.getInstance().getAppUsageTime(packageName);
                                long totalTime = usageStats.getTotalTimeInForeground();
                                return Math.max(0, totalTime - saveTotalTime);
                            }
                        }
                    }
                }
            }
        }
        if(packageName == null) {//为空时需要获取前台的packageName
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//android 7.0以上不支持
//                return 0;
//            }
            //compile 'com.jaredrummler:android-processes:1.1.1'
//            List<AndroidAppProcess> processes = AndroidProcesses.getRunningForegroundApps(SheepApp.getInstance());
//            AndroidAppProcess androidAppProcess = ListUtil.getLast(processes);
//            if (androidAppProcess != null) {
//                packageName = androidAppProcess.name;
//                appUsage.setPackageName(packageName);
//            }

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {//android 5.0以上不支持
                return 0;
            }
            android.app.ActivityManager.RunningAppProcessInfo process = getAppProcessInfoInForeground();
            if(process != null ) {
                packageName = process.processName;//没有packageName字段，可能会出问题
                appUsage.setPackageName(packageName);
            }
            if(TextUtils.isEmpty(packageName)){//没有获取到当前正在运行的应用
                return 0;
            }
        }
        long runTime = MyDbManager.getInstance().getAppRunTime(packageName);

        if(AutoTaskListUtil.getInstance().isLastAppRecord(packageName)){
            runTime +=  System.currentTimeMillis() - AutoTaskListUtil.getInstance().getLastTime();
        }
        return runTime;
    }

    public void println() {
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);//usagestats
            long time = System.currentTimeMillis();
            if(mUsageStatsManager != null) {
                List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, AutoTaskListUtil.getInstance().getReceiveTaskTime(), time);

                if (usageStatsList != null && !usageStatsList.isEmpty()) {
                    for (UsageStats usageStats : usageStatsList) {
                        if (usageStats != null ) {
                            LogUtil.println("AppUsageManager", usageStats.getPackageName());
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取应用最后使用时间
     * 24*60*60*1000
     */
    public long getAppLastUseTime(String pakageName, long intervalTime){
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            Calendar calendar=Calendar.getInstance();
            calendar.setTime(new Date());
            long endt = calendar.getTimeInMillis();//结束时间
            calendar.add(Calendar.DAY_OF_MONTH, -1);//时间间隔为一个月
            long statt = calendar.getTimeInMillis();//开始时间
            long time =System.currentTimeMillis()-intervalTime;
            UsageStatsManager usageStatsManager=(UsageStatsManager) SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);
            //获取一个月内的信息
            List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,statt,endt);
            if(queryUsageStats != null && queryUsageStats.size() > 0){
                for(UsageStats usageStats: queryUsageStats){
                    if(usageStats.getPackageName().equals(pakageName)){
                        return usageStats.getLastTimeUsed();
                    }
                }
            }
        }
        return 0;
    }
}
