package com.sheep.gamegroup.usage;

import android.app.AppOpsManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;

import com.sheep.gamegroup.model.entity.AppUsage;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.util.AutoTaskListUtil;
import com.sheep.gamegroup.util.ActivityManager;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

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;
    }

    /**
     * 需要开启查看应用使用情况的权限
     *
     * @return
     */
    public  boolean needOpenLookAppUsageStatsPermission(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 tryOpenLookAppUsageStatsPermission(boolean isSaveData) {
        if (!needOpenLookAppUsageStatsPermission(isSaveData)) {//不需要开启
            return;
        }
        if(AutoTaskListUtil.getInstance().isShowing()){//对话框仍在显示,就不显示 打开权限功能的对话框
            return;
        }
        LogUtil.println("tryOpenLookAppUsageStatsPermission", "start");
        AutoTaskListUtil.getInstance().clearAlertDialog();
        if(DataUtil.IS_LISTEN_SCREEN_SHOT){
            LogUtil.println("tryOpenLookAppUsageStatsPermission", "notEmpty");
            showAccessibilityDialog();
        } else {
            LogUtil.println("tryOpenLookAppUsageStatsPermission","else");
        }
        LogUtil.println("tryOpenLookAppUsageStatsPermission","end");
    }
    public void showAccessibilityDialog() {
        AlertDialog tipToOpenAccessibilityDialog = ViewUtil.showMsgDialog(ActivityManager.getInstance().currentActivity(), new DialogConfig().setTitle("温馨提示！")
                .setMsg("亲！系统检测到您需要手动开启小绵羊查看应用情况的权限才能继续任务！")
                .setBtnLeftText("去开启").setBtnLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        openLookAppUsageStatsPermission();
                    }
                }));
        tipToOpenAccessibilityDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                AutoTaskListUtil.getInstance().clearAlertDialog();
            }
        });
        AutoTaskListUtil.getInstance().setTipToOpenAccessibilityDialog(tipToOpenAccessibilityDialog);
    }
    public void openLookAppUsageStatsPermission(){
        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();
            }
        }
    }

    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, 1_514_736_000_000L, 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 packageName, long intervalTime){
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            long endTime = calendar.getTimeInMillis();//结束时间
            calendar.add(Calendar.DAY_OF_MONTH, -1);//时间间隔为一个月
            long startTime = calendar.getTimeInMillis();//开始时间
            UsageStatsManager usageStatsManager = (UsageStatsManager) SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);
            if (usageStatsManager != null) {
                //获取一个月内的信息
                List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, startTime, endTime);
                if (queryUsageStats != null && queryUsageStats.size() > 0) {
                    for (UsageStats usageStats : queryUsageStats) {
                        if (usageStats.getPackageName().equals(packageName)) {
                            return usageStats.getLastTimeUsed();
                        }
                    }
                }
            }
        }
        return 0;
    }

    //未开启查看应用使用情况的权限
    public static final long NOT_OPEN_USAGE_STATS = -1L;
    /**
     * 获取应用从2018-01-01 0:0:0到现在，在前台运行的时长
     * @param packageName
     * @return
     */
    public long getTotalTimeInForeground(String packageName) {
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) SheepApp.getInstance().getSystemService(USAGE_STATS_SERVICE);
            long time = System.currentTimeMillis();
            if(mUsageStatsManager != null) {
                List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 1_514_736_000_000L, time);//1_514_736_000_000L 对应 2018-01-01 0:0:0

                if (usageStatsList != null && !usageStatsList.isEmpty()) {
                    List<UsageStats> list = new ArrayList<>();
                    for (UsageStats usageStats : usageStatsList) {
                        if (usageStats != null && TextUtils.equals(packageName, usageStats.getPackageName())) {
                            list.add(usageStats);
                        }
                    }
                    //尝试修复重新第二天无法完成自动时长任务的bug
                    if(!list.isEmpty()){
                        long totalTimeInForeground = 0;
                        for (UsageStats usageStats : list) {
                            totalTimeInForeground += usageStats.getTotalTimeInForeground();
                        }
                        return totalTimeInForeground;
                    }
                } else {
                    return NOT_OPEN_USAGE_STATS;
                }
            }
        }
        return 0;
    }
}
