package com.android.launcher3.accessibility;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

import com.android.launcher3.manager.ColumnDef;
import com.android.launcher3.manager.Constants;
import com.android.launcher3.manager.LauncherManager;
import com.android.launcher3.manager.ManagementInfo;
import com.android.launcher3.model.ConfigManager;
import com.android.launcher3.util.Logger;
import com.android.launcher3.util.NotificationUtils;
import com.android.launcher3.util.WeakHandler;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

/**
 * 后台监听app的活动
 */
public class ListenerAppService extends Service {

    public static final String TAG = "ListenerAppService";

    public static final int POST_RUNNABLE = 0x1;

    public static final int COIN_USE_TIME_OUT = 0x2;

    public static final int INTERCEPT_SYSTEM_SETTING = 0x3;

    public static final int APP_CANT_USE = 0x4;

    public static final int APP_UNCLASS_TYPE = 0x5;

    public static final int APP_LOCKED = 0x6;

    public static final int APP_CLASS_USE_TIME_OUT = 0x7;


    private static final int TIME = 60 * 1000;

    private static final int LOOP_TIME = 1000;

    private volatile long lastUseAppControlTimeStamp;

    private boolean active = true;

    private InnerRecevier innerReceiver;
    private ExecutorService executors;


    private WeakHandler handler = new WeakHandler(this) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case POST_RUNNABLE:
                    if (active) {

                        if (!LauncherManager.getInstance().getExitState()) {
                            if (checkAppRunnable != null) {
                                if (checkAppRunnable.getStatus() == AsyncTask.Status.FINISHED) {
                                    checkAppRunnable = new CheckAppAsyncTask(this, getApplicationContext());
                                    checkAppRunnable.executeOnExecutor(executors);
                                } else if (checkAppRunnable.getStatus() == AsyncTask.Status.PENDING) {
                                    checkAppRunnable.executeOnExecutor(executors);
                                }
                            } else {
                                checkAppRunnable = new CheckAppAsyncTask(this, getApplicationContext());
                                checkAppRunnable.executeOnExecutor(executors);
                            }

//                            Logger.e(TAG,"POST_RUNNABLE RUN");
                        } else {
//                            Logger.e(TAG,"POST_RUNNABLE notRUN");
                        }

                    }
                    handler.sendEmptyMessageDelayed(POST_RUNNABLE, LOOP_TIME);
                    break;
                case INTERCEPT_SYSTEM_SETTING:
//                    LauncherManager.getInstance().backLauncherHome(getApplicationContext());
                    LauncherManager.getInstance().jumpSetting(getApplicationContext());
                    break;
                case COIN_USE_TIME_OUT:
                    LauncherManager.getInstance().backLauncherHome(getApplicationContext(), Constants.DIALOG_TYPE_COIN_NOT_ENOUGH);
                    break;
                case APP_CANT_USE:
                    LauncherManager.getInstance().backLauncherHome(getApplicationContext(), Constants.DIALOG_TYPE_APP_USE_DEADLINE);
                case APP_CLASS_USE_TIME_OUT:
                    LauncherManager.getInstance().backLauncherHome(getApplicationContext(), Constants.DIALOG_TYPE_SOME_CLASS_TIME_OUT);
                    break;
                case APP_UNCLASS_TYPE:
                    LauncherManager.getInstance().backLauncherHome(getApplicationContext(), Constants.DIALOG_TYPE_APP_UNCLASS);
                    break;
                case APP_LOCKED:
                    LauncherManager.getInstance().backLauncherHome(getApplicationContext(), Constants.DIALOG_TYPE_LOCKED);
                    break;


            }

        }
    };

    private CheckAppAsyncTask checkAppRunnable;

//    private

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        //创建广播
        innerReceiver = new InnerRecevier();
        //动态注册广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
//        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        intentFilter.addAction(Intent.ACTION_USER_PRESENT);
//        intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
//启动广播
        registerReceiver(innerReceiver, intentFilter);


//        registerReceiver()

        Logger.e(TAG, "onCreate");


        executors = Executors.newSingleThreadExecutor();

        checkAppRunnable = new CheckAppAsyncTask(handler, this);


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationUtils.ChannelBuilder channelBuilder = new NotificationUtils.ChannelBuilder("前台服务", "1111", "锁屏保护", NotificationManager.IMPORTANCE_DEFAULT)
                    .setChannelName("锁屏保护")
                    .setByPassDnd(false) //是否绕过免打扰
                    .setLightColor(Color.GREEN) //LED指示灯的颜色
                    .setShowBadge(false) //是否在桌面显示未读消息数量
                    .setEnableLight(false) //是否需要显示指示灯
                    .setEnableSound(false) //是否开启铃声
                    .setEnableVibrate(false) //是否开启震动
                    .setVisibility(NotificationCompat.VISIBILITY_SECRET); //锁屏界面是否可见


            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext(), channelBuilder);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), notificationUtils.getCurrentChannel());
            startForeground(1, builder.build());

        }


        handler.sendEmptyMessageDelayed(POST_RUNNABLE, LOOP_TIME);

//        usageStatsManager.
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        Logger.e(TAG, "onDestroy");
        if (innerReceiver != null) {
            unregisterReceiver(innerReceiver);
        }
        super.onDestroy();
    }

    public class InnerRecevier extends BroadcastReceiver {

        final String SYSTEM_DIALOG_REASON_KEY = "reason";

        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";

        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            Logger.e(TAG, action);

            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                if (!LauncherManager.getInstance().getExitState()) {
                    String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                    if (reason != null) {
                        Logger.e(TAG, action + "\t" + reason);
                        if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                            // "Home键被监听"
                            if (!LauncherManager.getInstance().isForceLock()) {
                                LauncherManager.getInstance().backLauncherHome(getApplicationContext());
                            } else {
//                            LauncherManager.getInstance().relockScreen();
                            }
                        } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                            if (!LauncherManager.getInstance().isForceLock()) {
                                LauncherManager.getInstance().backLauncherHome(getApplicationContext());
                            } else {
//                            LauncherManager.getInstance().relockScreen();
                            }
                        }
                    }
                }
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                active = false;
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {

                if (!LauncherManager.getInstance().isForceLock()) {
                    LauncherManager.getInstance().lockScreenNormal(getApplicationContext());
                }

                active = true;
            }
        }

    }


    public class CheckAppAsyncTask extends AsyncTask<Void, Void, Integer> {
        private WeakHandler handler;
        private Context context;

        private UsageStatsManager usageStatsManager;
        private PackageManager mPackageManager;


        public CheckAppAsyncTask(WeakHandler handler, Context context) {
            this.handler = handler;
            this.context = context;

            usageStatsManager = (UsageStatsManager) context.getSystemService(USAGE_STATS_SERVICE);
            mPackageManager = context.getPackageManager();
        }


        @Override
        protected Integer doInBackground(Void... voids) {


            Logger.e(TAG, "doInBackground\t");
            long currentMills = System.currentTimeMillis();

            if (LauncherManager.getInstance().getExitState())
                return -1;

            List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, currentMills - TIME, currentMills);

            //取得当前在前台的app，即当前运行的app
            if ((stats != null) && (!stats.isEmpty())) {
                String topActivity = "";
                int j = 0;
                for (int i = 0; i < stats.size(); i++) {
                    if (stats.get(i).getLastTimeUsed() > stats.get(j).getLastTimeUsed()) {
                        j = i;
                    }
                }

                Logger.e(TAG, lastUseAppControlTimeStamp + "\t" + stats.get(j).getLastTimeStamp() + "\t" + currentMills);

//                过滤重复的
                if (stats.get(j).getLastTimeUsed() < lastUseAppControlTimeStamp && lastUseAppControlTimeStamp > 0) {
                    return -1;
                }
                topActivity = stats.get(j).getPackageName();

                Logger.e(TAG, topActivity + "\t" + currentMills);

                if (LauncherManager.getInstance().isSafePackageName(topActivity) || LauncherManager.getInstance().isSystemPackageName(topActivity)) {
                    return -1;
                }

                if (LauncherManager.getInstance().updateLockScreenDelay()) {
                    return -1;
                }

                lastUseAppControlTimeStamp = currentMills;


                if (topActivity.equals(context.getPackageName()))
                    return -1;

                if (LauncherManager.getInstance().isInterceptSystemSetting() && "com.android.settings".equals(topActivity)) {

                    return INTERCEPT_SYSTEM_SETTING;
                }


                ManagementInfo appinfo = LauncherManager.getInstance().getManageAppInfo(topActivity);


                if (!LauncherManager.getInstance().isSafePackageName(topActivity) && !LauncherManager.getInstance().isSystemPackageName(topActivity)) {
                    if (appinfo != null) {
                        if (appinfo.getLock() == ColumnDef.LockApp.LOCKED) {
                            return APP_LOCKED;
                        } else if (appinfo.getUseType() == ColumnDef.AppUseType.UNCLASS_TYPE) {
                            return APP_UNCLASS_TYPE;
                        } else {
                            int type = LauncherManager.getInstance().canUse(topActivity);
                            if (type < 0) {
                                switch (type) {
                                    case -3:
                                        return APP_CLASS_USE_TIME_OUT;
                                    case -4:
                                        return COIN_USE_TIME_OUT;
                                    default:
                                        return APP_CANT_USE;
                                }
                            }
                        }
                    } else {
                        return APP_UNCLASS_TYPE;
                    }
                }
            } else {
                Logger.e(TAG, "stats list is empty");
                if (LauncherManager.getInstance().updateLockScreenDelay()) {
                    return -1;
                }
            }
            return -1;
        }


        @Override
        protected void onPostExecute(Integer integer) {
            int code = integer.intValue();

            if (code != -1) {
                handler.sendEmptyMessage(code);
            }
        }
    }
}


