package com.tool.applockpro.tool;

import android.app.AppOpsManager;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.provider.Settings;

import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.AdError;
import com.anythink.interstitial.api.ATInterstitial;
import com.anythink.interstitial.api.ATInterstitialListener;
import com.tool.applockpro.ApplockSkin;
import com.tool.applockpro.data.MyDataBase;
import com.tool.applockpro.data.Mydata;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Mytools {

    private static final String one_AD = "n66a73512bc4e5";
    private static final String two_Ad = "n66a734ffdcb74";
    private static final String three_ad = "n66a734e31e902";
    private static ArrayList<ATInterstitial> adArrayList;


    public static void setCallback(ATInterstitial ad, Adcallback adcallback) {
        ad.setAdListener(new ATInterstitialListener() {
            @Override
            public void onInterstitialAdLoaded() {
//                Log.e("zzj", "---------onInterstitialAdLoaded--------" + ad.mPlacementId);
            }

            @Override
            public void onInterstitialAdLoadFail(AdError adError) {
//                Log.e("zzj", "---------onInterstitialAdLoadFail--------" + adError.getFullErrorInfo());
                adcallback.onShowFail(adError);
            }

            @Override
            public void onInterstitialAdClicked(ATAdInfo atAdInfo) {

            }

            @Override
            public void onInterstitialAdShow(ATAdInfo atAdInfo) {
//                ad.load();
            }

            @Override
            public void onInterstitialAdClose(ATAdInfo atAdInfo) {
                adcallback.onAdHidden();
            }

            @Override
            public void onInterstitialAdVideoStart(ATAdInfo atAdInfo) {

            }

            @Override
            public void onInterstitialAdVideoEnd(ATAdInfo atAdInfo) {

            }

            @Override
            public void onInterstitialAdVideoError(AdError adError) {

            }
        });
    }

    public static ATInterstitial onCache(List<ATInterstitial> list) {
        Collections.shuffle(list);
        for (ATInterstitial ad : list) {
            if (ad.isAdReady()) {
                return ad;
            }
        }
        return null;
    }

    public static List<ATInterstitial> getAllAd() {
        if (adArrayList == null) {
            adArrayList = new ArrayList<>();
            adArrayList.add(createAd(one_AD, ApplockSkin.getContext()));
            adArrayList.add(createAd(two_Ad, ApplockSkin.getContext()));
            adArrayList.add(createAd(three_ad, ApplockSkin.getContext()));
        }
        for (ATInterstitial ad : adArrayList) {
            if (!ad.isAdReady()) {
                setCallback(ad, new Adcallback() {
                    @Override
                    public void onShowFail(AdError ad) {

                    }

                    @Override
                    public void onAdHidden() {

                    }
                });
//                ad.load();
            }
        }
        return adArrayList;
    }

    private static ATInterstitial createAd(String adUnitId, Context context) {
        ATInterstitial ad = new ATInterstitial(context, adUnitId);
        return ad;
    }


    public static String checkTopapp(Context context) {
        UsageStatsManager sUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        long endTime = System.currentTimeMillis();
        long beginTime = endTime - 10000;
        String result = "";
        UsageEvents.Event event = new UsageEvents.Event();
        UsageEvents usageEvents = sUsageStatsManager.queryEvents(beginTime, endTime);
        while (usageEvents.hasNextEvent()) {
            usageEvents.getNextEvent(event);
            if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                result = event.getPackageName();
            }
        }
        return result;
    }

    public static List<Mydata> getapplist(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0);
        List<Mydata> allapplist = new ArrayList<>();
        for (ResolveInfo resolveInfo : resolveInfos) {
            String packageName = resolveInfo.activityInfo.packageName;
            String appName = resolveInfo.loadLabel(packageManager).toString();
            Mydata data = new Mydata();
            data.setAppName(appName);
            data.setPackageName(packageName);
            if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                data.setSystem(false);
            } else {
                data.setSystem(true);
            }
            allapplist.add(data);
        }
        runIO(new Runnable() {
            @Override
            public void run() {
                List<Mydata> existingData = MyDataBase.getINSTANCE().mydao().getAllapp();
                if (!existingData.isEmpty()) {

                } else {
                    List<Mydata> uniqueSystemList = removeDuplApp(allapplist);
                    MyDataBase.getINSTANCE().mydao().insertAll(uniqueSystemList);
                }
            }
        });

        return allapplist;
    }

    private static List<Mydata> removeDuplApp(List<Mydata> appList) {
        Set<Mydata> uniqueApps = new LinkedHashSet<>(appList);
        return new ArrayList<>(uniqueApps);
    }

    public static boolean hasOverlayPermission(Context context) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return Settings.canDrawOverlays(context);
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean hasUsagePermission(Context context) {
        try {
            AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.getPackageName());
            return (mode == AppOpsManager.MODE_ALLOWED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static ExecutorService executorService;

    private static ExecutorService getExecutorService() {
        if (executorService == null) {
            executorService = Executors.newSingleThreadExecutor();
        }
        return executorService;
    }

    public static void runIO(Runnable task) {
        getExecutorService().execute(task);
    }


}
