package com.android.launcher3.accessibility;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
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.BitmapFactory;
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 android.util.Log;
import android.view.WindowManager;

import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.debug.CustomDialog;
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.PermissionUtil;
import com.android.launcher3.util.SystemUtils;
import com.android.launcher3.util.UIExecutor;
import com.android.launcher3.util.WeakHandler;

import org.json.JSONObject;

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 {

    private String notificationId = "launcher_3";
    private String notificationName = "1";

    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;

    public static final int APP_RESULT_HOME = 0x8;//回到桌面


    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 IntentFilter intentFilter;

    private NotificationManager notificationManager;


    @SuppressLint("HandlerLeak")
    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;
                case APP_RESULT_HOME://打开桌面
                    LauncherManager.getInstance().backLauncherHome(getApplicationContext());
                    break;
            }
        }
    };

    private CheckAppAsyncTask checkAppRunnable;

//    private

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


    @Override
    public void onCreate() {
        super.onCreate();
        //创建广播
        innerReceiver = new InnerRecevier();
        //动态注册广播
        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);
        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); //锁屏界面是否可见

            Intent home = new Intent(this, Launcher.class);
            home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            PendingIntent pendingIntent = PendingIntent.getActivity(this, 200, home, 0);


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

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

        }


        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //创建NotificationChannel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        startForeground(1, getNotification());
        notificationManager.notify(1, getNotification());


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

        final String SYSTEM_DIALOG_REASON_GESTURE_KEY = "fs_gesture";


        @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()) {
                    PermissionUtil.initLauncherIconIsShow(context, false);
                    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)) {
                            //PermissionUtil.initLauncherIconIsShow(context,false);
                            // "Home键被监听"
                            if (!LauncherManager.getInstance().isForceLock()) {
                                Log.i("launch_debug_show", "Home键监听");
                                toLauncherPage(context);
                            } else {
                                toLauncherPage(context);
                                LauncherManager.getInstance().relockScreen();
                            }
                        } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {//多任务监听
                            if (!LauncherManager.getInstance().isForceLock()) {
                                Log.i("launch_debug_show", "多任务按钮监听");
                                toLauncherPage(context);
                            } else {
                                toLauncherPage(context);
                                LauncherManager.getInstance().relockScreen();
                            }
                        } else if (reason.equals(SYSTEM_DIALOG_REASON_GESTURE_KEY)) {
                            if (!LauncherManager.getInstance().isForceLock()) {
                                Log.i("launch_debug_show", "手势");
                                toLauncherPage(context);
                            } else {
                                toLauncherPage(context);
                                LauncherManager.getInstance().relockScreen();
                            }
                        }
                    }
                } else {//没有管制，直接显示默认桌面app
                    if (LauncherManager.mCustomDialog != null) {
                        LauncherManager.mCustomDialog.dismiss();
                        LauncherManager.mCustomDialog = null;
                        Log.i("launch_debug_show", "关闭了进度条=" + Thread.currentThread());
                    }
                    PermissionUtil.initLauncherIconIsShow(context, true);
                }
            } 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());
                }
                //LauncherManager.getInstance().backLauncherHome(getApplicationContext());

                active = true;
            }
        }

    }


    private void toLauncherPage(Context context) {
        showProgress(context);
        LauncherManager.getInstance().backLauncherHome(getApplicationContext());
    }

    private void showProgress(Context context) {
        try {
            if (SystemUtils.isMEIZU()) {
                return;
            }
            if (LauncherManager.mCustomDialog == null) {
                LauncherManager.mCustomDialog = new CustomDialog(context.getApplicationContext(), R.layout.activity_clock_alarm);
                LauncherManager.mCustomDialog.show();
                Log.i("launch_debug_show", "显示了进度条");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


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

        private UsageStatsManager usageStatsManager;
        private PackageManager mPackageManager;
        private volatile String mLastPackage = "";


        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;

            //如果关闭了防止卸载则不拦截设置，否则拦截设置
            if (LauncherManager.getInstance().getUninstallEnable()) {
                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) {
                    topActivity = stats.get(j).getPackageName();
                    ManagementInfo appinfo = LauncherManager.getInstance().getManageAppInfo(topActivity);
                    if (appinfo != null) {
                        if (appinfo.getLock() != ColumnDef.LockApp.UNLOCKED) {
                            if (!mLastPackage.equals(topActivity))
                                lastUseAppControlTimeStamp = 0;
                        }
                        int type = LauncherManager.getInstance().canUse(topActivity);
                        if (type < 0) {
                            if (!mLastPackage.equals(topActivity))
                                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;


                Log.i("launch_debug_show", "当前顶部包名" + topActivity + "****" + "当前应用包名" + context.getPackageName());
                if (topActivity.equals(context.getPackageName()) || "android".equals(topActivity)) {
                    return -1;
                }

                if (LauncherManager.getInstance().isInterceptSystemSetting() && "com.android.settings".equals(topActivity)) {
                    return INTERCEPT_SYSTEM_SETTING;
                }

               /* if (LauncherManager.getInstance().isIsInterceptAppointPage() && LauncherManager.getInstance().isInterceptPackage(topActivity)) {
                    return INTERCEPT_SYSTEM_SETTING;
                }*/

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

                if (!LauncherManager.getInstance().isSafePackageName(topActivity) && !LauncherManager.getInstance().isSystemPackageName(topActivity)) {
                    if (appinfo != null) {
                        if (!mLastPackage.equals(topActivity)) {
                            mLastPackage = topActivity;
                        }
                        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 {
                        if (!LauncherManager.getInstance().isInterceptSystemSetting()) {//不拦截设置
                            return -1;
                        }
                        if (SystemUtils.isVIVO()) {
                            //toLauncherPage(context);
                            registerReceiver(innerReceiver, intentFilter);
                        }
                        return APP_RESULT_HOME;
                        //return -1;
                    }
                }
            } 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);
            }
           /* if (code == 200) {
                if (LauncherManager.mCustomDialog != null) {
                    LauncherManager.mCustomDialog.dismiss();
                    LauncherManager.mCustomDialog = null;
                    Log.i("launch_debug_show", "关闭了进度条=" + Thread.currentThread());
                }
            }*/
        }
    }

    private Notification getNotification() {

        Intent home = new Intent(this, Launcher.class);
        home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        home.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 200, home, 0);

        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_logo)
                .setContentTitle("“倍知守护孩子端”正在运行")
                .setContentText("倍知守护孩子端管控中")
                .setContentIntent(pendingIntent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(notificationId);
        }
        return builder.build();
    }
}


