package com.android.launcher3.auto_get_permission;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.android.launcher3.accessibility.PermissionOpenAccessiblityService;
import com.android.launcher3.manager.LauncherManager;
import com.android.launcher3.util.KToast;
import com.android.launcher3.util.Logger;
import com.android.launcher3.util.PermissionUtil;
import com.android.launcher3.util.SystemUtils;

import static android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK;
import static android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_HOME;

public abstract class BaseAutoGetPermission {
//    设备管理器
    public static final int STEP_REQUEST_DEVICE_ADMIN = 1;
//    自启动
    public static final int STEP_REQUEST_AUTO_STARTUP = 2;
//    忽略电量优化
    public static final int STEP_REQUEST_BATTERY_OPTIMIZE = 3;
//    使用记录访问权限
    public static final int STEP_REQUEST_APP_USAGE= 4;
//    关闭USB调试
    public static final int STEP_REQUEST_CLOSE_USB = 5;
//    通知访问使用权
    public static final int STEP_REQUEST_NOTIFICATION_MANAGER= 6;
//    默认桌面
    public static final int STEP_REQUEST_DEFAULT_LAUNCHER = 7;


    private static final String TAG = "BaseAutoGetPermission";
    public static final long MAX_SEARCH_TIME = 4000;
    public static final int BREAK_WHILE = 2;

//    public static String appName = "倍知守护孩子端";

    public static String appName = "dankal_launcher";
    public boolean isRunning;
    private KToast toast;

    private PermissionOpenAccessiblityService service;

    //    private boolean breadWhile = false;
    private Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (!isRunning) {
                        service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                    }
                    break;
            }
        }
    };

    public BaseAutoGetPermission(PermissionOpenAccessiblityService service) {
        this.service = service;
        isRunning = false;
        isFinish = false;
        handler.sendEmptyMessageDelayed(0, 1000);
//        Logger.e(TAG, "onServiceConnected\t");
        service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
        showToastLong("辅助权限设置已开启，请根据提示点击，如无提示请等待片刻");
        toast = new KToast(service.getApplicationContext());
    }

    private boolean isFinish = false;
    public int step;

    public void start() {
        isRunning = true;
    }


    public void stop() {
        isRunning = false;
    }


    public void operateAccessibilityEvent(AccessibilityEvent event) {
        if (step == STEP_REQUEST_DEVICE_ADMIN) {
            if (event.getClassName() != null) {


                if (event.getSource() != null) {

                    if (PermissionUtil.checkDeviceAdminPermission(getApplicationContext())) {
                        resetStep();
                    } else {
                        requestkDeviceAdmin(event);
                    }

                } else {

                    if (SystemUtils.isOPPO()) {

                        if ("android.widget.FrameLayout".equals(event.getClassName()) && event.getPackageName().equals("com.sohu.inputmethod.sogouoem")) {

                            showToastLong("请在此处手动输入验证码");
                        }
                    }
                }
            }
        }



        if (step == STEP_REQUEST_AUTO_STARTUP) {
            if (event.getClassName() != null) {

                if (event.getSource() == null)
                    return;
                if (PermissionUtil.checkAutoStartUp(getApplicationContext())) {
                    resetStep();
                } else {
                    reqeustAutoStartUp(event);
                }

            }
        }

        if (step == STEP_REQUEST_BATTERY_OPTIMIZE) {
            if (event.getClassName() != null) {

                if (SystemUtils.isNOKIA() && event.getSource() == null) {
                    getService().performGlobalAction(GLOBAL_ACTION_HOME);
                    getService().performGlobalAction(GLOBAL_ACTION_BACK);
                }
                if (event.getSource() != null) {

                    if (PermissionUtil.checkBatteryOptimize(getApplicationContext())) {
                        resetStep();
                    } else {

                        requestBatteryOptimize(event);
                    }
                }
            }
        }

        if (step == STEP_REQUEST_APP_USAGE) {
            if (event.getClassName() != null) {
                if (event.getSource() != null) {
                    if (PermissionUtil.checkAppUsagePermission(getApplicationContext())) {
                        resetStep();
                    } else {
                        requestUsageAppPermission(event);
                    }
                }
            }
        }

        if (step == STEP_REQUEST_CLOSE_USB) {
            if (event.getClassName() != null) {

                if (event.getSource() == null)
                    return;
                if (!PermissionUtil.enAbleADB(getApplicationContext())) {
                    resetStep();
                } else {
                    requestCloseUSB(event);
                }
            }
        }
        if (step == STEP_REQUEST_NOTIFICATION_MANAGER) {
            if (event.getClassName() != null) {

                if (event.getSource() == null)
                    return;
                if (PermissionUtil.isNotificationListenersEnabled(getApplicationContext())) {
                    resetStep();
                } else {
                    requestNotificationPermission(event);
                }

            }
        }


        //设置默认桌面
        if (step == STEP_REQUEST_DEFAULT_LAUNCHER) {
            if (PermissionUtil.isDefaultHome(getApplicationContext()))
                return;

            if (event.getSource() == null)
                return;

            if (event.getClassName() == null)
                return;

            if (PermissionUtil.isDefaultHome(getApplicationContext())) {
                resetStep();
            } else {
                requestDefaultLauncher(event);
            }

        }



        if (!PermissionUtil.checkDeviceAdminPermission(getApplicationContext())) {


            if (step != STEP_REQUEST_DEVICE_ADMIN) {
                if (SystemUtils.isMIUI()) {

                    if (event.getClassName().toString().contains("com.android.settings")) {
                        step = STEP_REQUEST_DEVICE_ADMIN;
                        operateAccessibilityEvent(event);
                        return;
                    }


                }
                gotoDeviceAdminPermissionSetting();
                sleep();

                return;
            }
            if (step == STEP_REQUEST_DEVICE_ADMIN) {
                if (PermissionUtil.checkDeviceAdminPermission(getApplicationContext())) {
                    resetStep();
                } else {
                    return;
                }

            }
        }

        if (!PermissionUtil.checkAutoStartUp(getApplicationContext())) {
            if (step != STEP_REQUEST_AUTO_STARTUP) {
                if (SystemUtils.isMIUI()) {
                    if (event.getClassName().toString().contains("com.android.settings")) {
                        step = STEP_REQUEST_AUTO_STARTUP;
                        operateAccessibilityEvent(event);
                    }
                }
                gotoAutoStartUpSetting();
                sleep();
                return;
            }

            if (step == STEP_REQUEST_AUTO_STARTUP) {
                if (PermissionUtil.checkAutoStartUp(getApplicationContext())) {
                    resetStep();
                } else {
//                        if (SystemUtils.isNOKIA()) {
//                            if (event.getSource() != null) {
//                                requestBatteryOptimize(event);
//                            }
//                        }

                    return;
                }
            }
        }


        if (!PermissionUtil.checkBatteryOptimize(getApplicationContext())) {

            if (step != STEP_REQUEST_BATTERY_OPTIMIZE) {
                if (SystemUtils.isMIUI()) {
                    if (event.getClassName().toString().contains("com.android.settings")) {
                        step = STEP_REQUEST_BATTERY_OPTIMIZE;
                        operateAccessibilityEvent(event);
                    }
                }
                gotoBatteryOptimize();
                sleep();
                return;
            }

            if (step == STEP_REQUEST_BATTERY_OPTIMIZE) {
                if (PermissionUtil.checkBatteryOptimize(getApplicationContext())) {
                    resetStep();
                } else {
//                        if (SystemUtils.isNOKIA()) {
//                            if (event.getSource() != null) {
//                                requestBatteryOptimize(event);
//                            }
//                        }

                    return;
                }
            }

        }

        if (!PermissionUtil.checkAppUsagePermission(getApplicationContext())) {

            if (step != STEP_REQUEST_APP_USAGE) {
                gotoAppUsagePermission();
                sleep();
                return;
            }

            if (step == STEP_REQUEST_APP_USAGE) {
                if (PermissionUtil.checkAppUsagePermission(getApplicationContext())) {
                    resetStep();
                } else {
//                        requestUsageAppPermission(event);
                    return;
                }
            }


        }

        if (PermissionUtil.enAbleADB(getApplicationContext())) {

            if (step != STEP_REQUEST_CLOSE_USB) {

                gotoDeveloperChoice();
                sleep();
                requestCloseUSB(event);
                return;
            }

            if (step == STEP_REQUEST_CLOSE_USB) {
                if (!PermissionUtil.enAbleADB(getApplicationContext())) {
                    resetStep();
                } else {
//                        requestCloseUSB(event);
                    return;
                }

            }

        }


        if (!PermissionUtil.isNotificationListenersEnabled(getApplicationContext())) {
            if (step != STEP_REQUEST_NOTIFICATION_MANAGER) {
                gotoNotificationSettings();
                sleep();
                requestNotificationPermission(event);
                return;
            }

            if (step == STEP_REQUEST_NOTIFICATION_MANAGER) {
                if (PermissionUtil.isNotificationListenersEnabled(getApplicationContext())) {
                    resetStep();
                } else {
//                        requestNotificationPermission(event);
                    return;
                }
            }

        }

        if (!PermissionUtil.isDefaultHome(getApplicationContext())) {

            if (step != STEP_REQUEST_DEFAULT_LAUNCHER) {
                if (!SystemUtils.isMEIZU()) {
                    gotoDefaultLauncherSetting();
                } else {
                    //8.0设置换了布局viewid
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                        gotoDefaultLauncherSetting();
                    } else {
                        gotoSystemSettings();
                    }

                }

                sleep();

                return;
            }

            if (step == STEP_REQUEST_DEFAULT_LAUNCHER) {
                if (PermissionUtil.isDefaultHome(getApplicationContext())) {
                    resetStep();
                } else {
                    return;
                }
            }

        }

        finish();

    }

    public void showToastLong(String msg) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Logger.e(TAG, "showToastLong\t" + msg);
                toast.setText("倍知守护提醒您 : \n" + msg);
                toast.show();
            }
        });
    }


    public void finish() {
        if (!isFinish) {
            isFinish = true;
            service.finish();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                service.disableSelf();
            }
        }
    }

    /**
     * 跳转之后停顿等待一会
     */
    public void sleep() {
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void sleepLong() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void sleepLongLong() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void sleepShort() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void sleepWarnningDialogByXiaomi() {
        try {
            Logger.e(TAG, "sleepWarnningDialogByXiaomi start");
            Thread.sleep(5000);
            Logger.e(TAG, "sleepWarnningDialogByXiaomi\t" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            Logger.e(TAG, "sleepWarnningDialogByXiaomi InterruptedException");
        }
    }


    public boolean performAction(AccessibilityNodeInfo accessibilityNodeInfo1, int action) {
        boolean result = false;
        if (accessibilityNodeInfo1 != null) {
            if (accessibilityNodeInfo1.isClickable()) {
                result = accessibilityNodeInfo1.performAction(action);

                Logger.e(TAG, "child \t" + result);
//                if (result) {
//                    dismissToast();
//                    return result;
//                }

            } else {
                if (accessibilityNodeInfo1.getParent() != null) {
                    result = accessibilityNodeInfo1.getParent().performAction(action);

                    Logger.e(TAG, "parent\t" + result);
//                    if (result) {
//                        dismissToast();
//                        return result;
//                    }
                }
            }

            if (!result && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Rect bounds = new Rect();
                accessibilityNodeInfo1.getBoundsInScreen(bounds);


                result = AccessibilityNodeOperateUtil.click(service, bounds);

                Logger.e(TAG, "android o genture\t" + result);
//                if (result) {
//                    dismissToast();
//                    return result;
//                }
            }
        }

        return result;
    }

    public boolean clickXiaomiSafeWarning(AccessibilityNodeInfo sourceNode) {
        int count = 3;
        Logger.e(TAG, "clickXiaomiSafeWarning");

        while (count > 0) {
            Logger.e(TAG, "enter DeviceManagerApplyActivity");
            sleepWarnningDialogByXiaomi();
            AccessibilityNodeInfo nextStepNodeInfo = AccessibilityNodeOperateUtil.getChildNodeEqual(sourceNode, "下一步");

            if (nextStepNodeInfo != null) {
                nextStepNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                --count;
            }

            AccessibilityNodeInfo allowBtnNode = AccessibilityNodeOperateUtil.getChildNodeEqual(sourceNode, "允许");
            if (allowBtnNode != null) {
                allowBtnNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                --count;
                return true;
            }
        }

        return false;
    }

    public Context getApplicationContext() {
        return service.getApplicationContext();
    }


    public void resetStep() {


//        针对某些机型获取权限之后短暂时间内依然返回false
//        if (step == 1) {
//            PermissionUtil.isAdminDevice = true;
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//
//            PermissionUtil.isAdminDevice = false;
//        }


        if (step == STEP_REQUEST_BATTERY_OPTIMIZE) {
//            if (SystemUtils.isMIUI()) {
            PermissionUtil.isBatterySaveClose = true;
//            }
        }

        step = 0;
        service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
    }

    public AccessibilityService getService() {
        return service;
    }


    public void gotoDeviceAdminPermissionSetting() {
        step = STEP_REQUEST_DEVICE_ADMIN;
        PermissionUtil.gotoDeviceAdminPermissionSetting(getApplicationContext());
    }


    public void gotoAutoStartUpSetting() {
        step = STEP_REQUEST_AUTO_STARTUP;
        PermissionUtil.gotoAutoStartUpSettings(getApplicationContext());

    }

    public void gotoBatteryOptimize() {
        step = STEP_REQUEST_BATTERY_OPTIMIZE;
        PermissionUtil.gotoBatteryOptimize(getApplicationContext());

    }


    public void gotoAppUsagePermission() {
        if (SystemUtils.isMIUI()) {
            PermissionUtil.gotoSystemSetting(getApplicationContext());
        } else {
            PermissionUtil.gotoAppUsagePermission(getApplicationContext());
        }
        step = STEP_REQUEST_APP_USAGE;
    }

    public void gotoDeveloperChoice() {
        PermissionUtil.gotoDeveloperChoice(getApplicationContext());
        step = STEP_REQUEST_CLOSE_USB;
    }

    public void gotoNotificationSettings() {
        PermissionUtil.goToNotificationAccessSetting(getApplicationContext());
        step = STEP_REQUEST_NOTIFICATION_MANAGER;
    }

    public void gotoDefaultLauncherSetting() {
        PermissionUtil.setDefaultL(getApplicationContext());
        step = STEP_REQUEST_DEFAULT_LAUNCHER;
    }


    public void gotoSystemSettings() {
        PermissionUtil.gotoSystemSetting(getApplicationContext());
        step = STEP_REQUEST_DEFAULT_LAUNCHER;
    }


    public abstract void requestkDeviceAdmin(AccessibilityEvent event);

    public abstract void reqeustAutoStartUp(AccessibilityEvent event);

    public abstract void requestBatteryOptimize(AccessibilityEvent event);

    public abstract void requestUsageAppPermission(AccessibilityEvent event);

    public abstract void requestCloseUSB(AccessibilityEvent event);

    public abstract void requestNotificationPermission(AccessibilityEvent event);

    public abstract void requestDefaultLauncher(AccessibilityEvent event);
}
