package com.sheep.gamegroup.util;

import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.os.Build;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeMap;

/**
 * Created by realicing on 2018/9/20.
 * realicing@sina.com
 */
public class RunningTaskUtil {
    private static final String TAG="RunningTaskUtil";
    public static final int TWENTYSECOND = 1000 * 20;
    public static final int THIRTYSECOND = 1000 * 60 * 60 * 3;
    private UsageStatsManager mUsageStatsManager;
    private Field mLastEventField;
    private Context context;
    public RunningTaskUtil(Context context){
        this.context = context;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1){
            mUsageStatsManager = (UsageStatsManager)context.getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);
        }
    }

    public String getTopRunningTasks(){
        //用两次取当前应用的办法来提高正确性
        return getTopRunningTasks(true);
    }

    public String getTopRunningTasks(boolean isFirst){
        String topPackageName =null;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
            long time = System.currentTimeMillis();
            // We get usage stats for the last 10 seconds
            List<UsageStats> stats ;
            if (isFirst){
                stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - TWENTYSECOND, time);
            }else {
                stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - THIRTYSECOND, time);
            }
            // Sort the stats by the last time used
            if(stats != null) {
                TreeMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
                for (UsageStats usageStats : stats) {
                    mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
                }
                if(!mySortedMap.isEmpty()) {
                    NavigableSet<Long> keySet=mySortedMap.navigableKeySet();
                    Iterator<Long> iterator=keySet.descendingIterator();
                    while(iterator.hasNext()){
                        UsageStats usageStats = mySortedMap.get(iterator.next());
                        if (mLastEventField==null) {
                            try {
                                mLastEventField = UsageStats.class.getField("mLastEvent");
                            } catch (NoSuchFieldException e) {
                                break;
                            }
                        }
                        if (mLastEventField!=null) {
                            int lastEvent;
                            try {
                                lastEvent = mLastEventField.getInt(usageStats);
                            } catch (IllegalAccessException e) {
                                break;
                            }
                            if (lastEvent==1){
                                topPackageName=usageStats.getPackageName();
                                break;
                            }
                        }else {
                            break;
                        }
                    }
                    if (topPackageName==null){
                        topPackageName =  mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                        if ("com.android.systemui".equals(topPackageName)){
                            Long currentKey = null;
                            String tempPackage = topPackageName;
                            currentKey = (Long) ((TreeMap) mySortedMap).floorKey(mySortedMap.lastKey()-1);
                            if (currentKey!=null) {
                                tempPackage = mySortedMap.get(currentKey).getPackageName();
                            }
                            if (tempPackage!=null){
                                if (context.getPackageName().equals(tempPackage)){
                                    currentKey = (Long) ((TreeMap) mySortedMap).floorKey(currentKey-1);
                                    if (currentKey!=null) {
                                        tempPackage = mySortedMap.get(currentKey).getPackageName();
                                    }
                                }
                            }
                            if (tempPackage!=null){
                                topPackageName=tempPackage;
                            }
                        }
                    }
                }else {
                    if (isFirst){
                        topPackageName = getTopRunningTasks(false);
                    }
                }
            }
        }
        return topPackageName;
    }

    public String getTopRunningTasksOrigin(){
        String topPackageName =null;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
            long time = System.currentTimeMillis();
            // We get usage stats for the last 10 seconds
            List<UsageStats> stats ;
            stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - TWENTYSECOND, time);
            // Sort the stats by the last time used
            if(stats != null) {
                TreeMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
                for (UsageStats usageStats : stats) {
                    mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
                }
                if(!mySortedMap.isEmpty()) {
                    topPackageName =  mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                }
            }
        }
        return topPackageName;
    }

}
