package com.android.launcher3.auto_get_permission.meizu;

import android.accessibilityservice.AccessibilityService;
import android.os.Build;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.android.launcher3.accessibility.PermissionOpenAccessiblityService;
import com.android.launcher3.auto_get_permission.BaseAutoGetPermission;
import com.android.launcher3.util.Logger;
import com.android.launcher3.util.SystemUtils;

import java.util.List;

import static android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK;
import static com.android.launcher3.auto_get_permission.AccessibilityNodeOperateUtil.*;

public class MeizuAutoPermissionGetter extends BaseAutoGetPermission {

    private static final String TAG = "MeizuAutoPermissionGetter";

    public MeizuAutoPermissionGetter(PermissionOpenAccessiblityService service) {
        super(service);
    }

    @Override
    public void requestkDeviceAdmin(AccessibilityEvent event) {

    }

    @Override
    public void reqeustAutoStartUp(AccessibilityEvent event) {

    }

    @Override
    public void requestBatteryOptimize(AccessibilityEvent event) {
        AccessibilityNodeInfo sourceNode = event.getSource();
        //                 魅族   权限管理 ->后台管理-> 打开应用开关
        if ("com.meizu.safe.SecurityMainActivity".equals(event.getClassName().toString())) {
//                            手机管家页面

            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeEqual(sourceNode, "权限管理");

            if (accessibilityNodeInfo1 != null && accessibilityNodeInfo1.getParent() != null) {
                Logger.e(TAG, accessibilityNodeInfo1.getParent().toString());

                boolean success = performAction(accessibilityNodeInfo1, AccessibilityNodeInfo.ACTION_CLICK);
                if (!success) {
                    sleep();
                } else {
                    showToastLong("请点击【权限管理】");
                    return;
                }
            }

            return;
        }

        if ("com.meizu.safe.permission.PermissionMainActivity".equals(event.getClassName().toString())) {
//                            权限管理页面
            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeEqual(sourceNode, "后台管理");
            if (accessibilityNodeInfo1 != null && performAction(accessibilityNodeInfo1, AccessibilityNodeInfo.ACTION_CLICK)) {
                sleep();
            } else {
                showToastLong("请点击【后台管理】");
                return;
            }


            return;
        }

        if ("com.meizu.safe.permission.SmartBGActivity".equals(event.getClassName().toString())) {

            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeByIdEqualText(sourceNode, "com.meizu.safe:id/name", appName);

            List<AccessibilityNodeInfo> nodeInfoList = sourceNode.findAccessibilityNodeInfosByViewId("com.meizu.safe:id/list");

            if (nodeInfoList != null && nodeInfoList.size() > 0) {
                AccessibilityNodeInfo listViewNode = nodeInfoList.get(0);
                long time = System.currentTimeMillis();
                while (accessibilityNodeInfo1 == null && System.currentTimeMillis() - time < MAX_SEARCH_TIME) {
                    if (listViewNode == null) {
                        break;
                    }

                    if (listViewNode.isScrollable()) {
                        listViewNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                        sleepShort();
                        listViewNode.refresh();
                    } else {
                        break;
                    }

                    accessibilityNodeInfo1 = getChildNodeByIdEqualText(sourceNode, "com.meizu.safe:id/name", appName);
                }

            }

            if (accessibilityNodeInfo1 != null && performAction(accessibilityNodeInfo1, AccessibilityNodeInfo.ACTION_CLICK)) {

            } else {
                showToastLong("请找到【" + appName + "】应用并点击");
                return;
            }


        }

        if ("android.app.AlertDialog".equals(event.getClassName().toString())) {

            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeEqual(sourceNode, "允许后台运行");

            if (accessibilityNodeInfo1 != null && performAction(accessibilityNodeInfo1, AccessibilityNodeInfo.ACTION_CLICK)) {
                resetStep();
            } else {
                showToastLong("请点击【允许后台运行】");
                return;
            }
        }
    }

    @Override
    public void requestUsageAppPermission(AccessibilityEvent event) {
        AccessibilityNodeInfo sourceNode = event.getSource();

        if ("com.android.settings.Settings$UsageAccessSettingsActivity".equals(event.getClassName())) {
            getChildNodeEqual(sourceNode, appName);
            sleep();

            List<AccessibilityNodeInfo> appListNodeList = null;

//                getChildNodeEqual(sourceNode,appName);
            appListNodeList = sourceNode.findAccessibilityNodeInfosByViewId("android:id/list");

            if (appListNodeList == null || appListNodeList.isEmpty()) {
//
                appListNodeList = sourceNode.findAccessibilityNodeInfosByViewId("com.android.settings:id/apps_list");
            }


            if (appListNodeList != null && appListNodeList.size() > 0) {
                AccessibilityNodeInfo appListNode = appListNodeList.get(0);

                AccessibilityNodeInfo targetAppItem = null;

                targetAppItem = getChildNodeByIdEqualText(appListNode, "com.android.settings:id/app_name", appName);
                if (targetAppItem == null) {

                    targetAppItem = getChildNodeByIdEqualText(appListNode, "android:id/title", appName);
                }

                long time = System.currentTimeMillis();
                while (targetAppItem == null && System.currentTimeMillis() - time < MAX_SEARCH_TIME) {

                    if (appListNode.isScrollable()) {
                        appListNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                        sleepShort();
                        appListNode.refresh();
                        targetAppItem = getChildNodeByIdEqualText(appListNode, "com.android.settings:id/app_name", appName);
                        if (targetAppItem == null) {

                            targetAppItem = getChildNodeByIdEqualText(appListNode, "android:id/title", appName);
                        }
                    } else {
                        break;
                    }
                }

                if (!performAction(targetAppItem, AccessibilityNodeInfo.ACTION_CLICK)) {
                    showToastLong("请找到【" + appName + "】并点击");
                    return;
                } else {
                    List<AccessibilityNodeInfo> switcherNodeList = targetAppItem.getParent().findAccessibilityNodeInfosByViewId("com.android.settings:id/app_switch");

                    if (switcherNodeList != null && !switcherNodeList.isEmpty() && performAction(switcherNodeList.get(0), AccessibilityNodeInfo.ACTION_CLICK)) {
                        sleepShort();
//                                resetStep();
                    }
                }

            }
        } else if ("android.app.AlertDialog".equals(event.getClassName())) {
            AccessibilityNodeInfo allowNode = getChildNodeEqual(sourceNode, "允许");
            if (allowNode == null) {
                allowNode = getChildNodeEqual(sourceNode, "确定");
            }

            if (performAction(allowNode, AccessibilityNodeInfo.ACTION_CLICK)) {
                sleep();
                resetStep();
            } else {
                showToastLong("请点击【确定】");
                return;
            }
        }


        /**
         * 使用记录访问权限(华为设备不同设备标题不同)
         */
        if ("com.android.settings.SubSettings".equals(event.getClassName()) && event.getText() != null && (event.getText().toString().contains("使用情况访问权限") || event.getText().toString().contains("使用记录访问权限") || event.getText().toString().contains("使用量数据访问"))) {

            if (SystemUtils.isSAMSUNG()) {
                AccessibilityNodeInfo nodeInfo = getChildNodeEqual(sourceNode, "允许追踪使用情况");

                if (performAction(nodeInfo, AccessibilityNodeInfo.ACTION_CLICK)) {

                    sleepShort();
                    resetStep();
                } else {
                    showToastLong("请点击【允许追踪使用情况】并返回上一页");
                    return;
                }
            } else if (SystemUtils.isNOKIA()) {
                sleep();
                List<AccessibilityNodeInfo> switchWidgetNodeList = sourceNode.findAccessibilityNodeInfosByViewId("android:id/switch_widget");

                if (switchWidgetNodeList != null && switchWidgetNodeList.size() > 0) {

                    if (switchWidgetNodeList.get(0).isChecked()) {
                        resetStep();

                    }

                    switchWidgetNodeList.get(0).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    resetStep();

                }

            } else {
                AccessibilityNodeInfo textViewNode = getChildNodeByIdEqualText(sourceNode, "android:id/title", "允许访问使用记录");

                if (textViewNode != null && textViewNode.getParent() != null) {
                    if (textViewNode.getParent().isClickable()) {
                        textViewNode.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        resetStep();
                    }
                } else {
                    textViewNode = getChildNodeByIdEqualText(sourceNode, "android:id/title", "允许查看使用情况");
                    if (performAction(textViewNode, AccessibilityNodeInfo.ACTION_CLICK)) {
                        resetStep();
                    } else {
                        showToastLong("请点击【允许查看使用情况】并返回上一页");
                        return;
                    }
                }
            }
        }
    }

    @Override
    public void requestCloseUSB(AccessibilityEvent event) {
        AccessibilityNodeInfo sourceNode = event.getSource();
        if ("com.android.settings.Settings$DevelopmentSettingsActivity".equals(event.getClassName()) && event.getText() != null && event.getText().toString().contains("开发者选项")) {
            AccessibilityNodeInfo usbNode = getChildNodeEqual(sourceNode, "USB 调试");
            if (performAction(usbNode, AccessibilityNodeInfo.ACTION_CLICK)) {

                resetStep();
            } else {
                showToastLong("请点击【USB 调试】");
                return;
            }

        }
    }

    @Override
    public void requestNotificationPermission(AccessibilityEvent event) {
        AccessibilityNodeInfo sourceNode=event.getSource();
        if ("com.android.settings.Settings$NotificationAccessSettingsActivity".equals(event.getClassName())) {

            AccessibilityNodeInfo targetApp = getChildNodeEqual(sourceNode, appName);
            if (!performAction(targetApp, AccessibilityNodeInfo.ACTION_CLICK)) {
                List<AccessibilityNodeInfo> nodeInfoList = sourceNode.findAccessibilityNodeInfosByViewId("com.android.settings:id/list");
                if (nodeInfoList != null && nodeInfoList.size() > 0) {
                    AccessibilityNodeInfo listViewNode = nodeInfoList.get(0);

                    AccessibilityNodeInfo targetAppItem = getChildNodeByIdEqualText(listViewNode, "android:id/title", appName);
                    long time = System.currentTimeMillis();
                    while (targetAppItem == null && System.currentTimeMillis() - time < MAX_SEARCH_TIME) {
                        if (listViewNode != null) {

                            if (listViewNode.isScrollable()) {
                                listViewNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                                sleepShort();
                                listViewNode.refresh();
                            }
                        }

                        targetAppItem = getChildNodeByIdEqualText(listViewNode, "android:id/title", appName);


                    }

                    if (!performAction(targetAppItem, AccessibilityNodeInfo.ACTION_CLICK)) {
                        showToastLong("请点击【" + appName + "】");
                        return;
                    }
                } else {
                    showToastLong("请点击【" + appName + "】");
                }
            }


        }

        if ("android.app.AlertDialog".equals(event.getClassName())) {
//                            允许
            List<AccessibilityNodeInfo> nodeInfoList = sourceNode.findAccessibilityNodeInfosByViewId("android:id/button1");
            if (nodeInfoList != null && nodeInfoList.size() > 0 && performAction(nodeInfoList.get(0), AccessibilityNodeInfo.ACTION_CLICK)) {

                resetStep();
                return;

            } else {
                showToastLong("请点击【允许】");
                return;
            }
        }
    }

    @Override
    public void requestDefaultLauncher(AccessibilityEvent event) {

        AccessibilityNodeInfo nodeInfo=event.getSource();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {

            if ("com.android.internal.app.MzResolverActivity".equals(event.getClassName())) {
                AccessibilityNodeInfo checkBoxNode = getChildNodeEqual(nodeInfo, "默认使用该应用打开");

                if (performAction(checkBoxNode, AccessibilityNodeInfo.ACTION_CLICK)) {

                    sleepShort();

                } else {
                    showToastLong("请点击【默认使用该应用打开】");
                    return;
                }
                AccessibilityNodeInfo targetAppNode = getChildNodeEqual(nodeInfo, appName);

                if (performAction(targetAppNode, AccessibilityNodeInfo.ACTION_CLICK)) {
                    sleepShort();
                } else {
                    showToastLong("请点击【" + appName + "】");
                    return;
                }
            }
        } else {
            if ("com.android.settings.Settings".equals(event.getClassName().toString())) {
//                设置页面

                List<AccessibilityNodeInfo> recycleListNodes = nodeInfo.findAccessibilityNodeInfosByViewId("com.android.settings:id/list");
                if (recycleListNodes != null && !recycleListNodes.isEmpty()) {
                    AccessibilityNodeInfo recyclerListNode = recycleListNodes.get(0);
                    AccessibilityNodeInfo appManageNode = getChildNodeEqual(recyclerListNode, "应用管理");

                    long time = System.currentTimeMillis();
                    while (appManageNode == null && System.currentTimeMillis() - time < MAX_SEARCH_TIME) {
                        if (recyclerListNode.isScrollable()) {
                            recyclerListNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                            recyclerListNode.refresh();

                        } else {
                            break;
                        }
                        appManageNode = getChildNodeEqual(recyclerListNode, "应用管理");
                    }

                    if (performAction(appManageNode, AccessibilityNodeInfo.ACTION_CLICK)) {

                        sleepShort();

                        return;
                    } else {
                        showToastLong("请点击【应用管理】");
                        return;
                    }

                }


            } else if ("com.android.settings.Settings$ManageApplicationsActivity".equals(event.getClassName().toString())) {
                AccessibilityNodeInfo defaultLauncherNode = getChildNodeEqual(nodeInfo, "默认应用");
                if (performAction(defaultLauncherNode, AccessibilityNodeInfo.ACTION_CLICK)) {


                    sleepShort();
                    return;
                } else {
                    showToastLong("请点击【默认应用】");
                    return;
                }

            } else if ("com.android.settings.SubSettings".equals(event.getClassName().toString())) {

                if (event.getText() != null && !TextUtils.isEmpty(event.getText().toString())) {
                    if ("[默认应用]".equals(event.getText().toString())) {
                        AccessibilityNodeInfo launcherNode = getChildNodeEqual(nodeInfo, "桌面");

                        if (performAction(launcherNode, AccessibilityNodeInfo.ACTION_CLICK)) {

                            sleepShort();
                            return;
                        } else {
                            showToastLong("请点击【桌面】");
                            return;
                        }
                    } else if ("[桌面]".equals(event.getText().toString())) {
                        AccessibilityNodeInfo targetNode = getChildNodeEqual(nodeInfo, appName);

                        if (performAction(targetNode, AccessibilityNodeInfo.ACTION_CLICK)) {


                            sleepShort();

                            return;
                        } else {
                            showToastLong("请点击【" + appName + "】");
                            return;
                        }
                    }
                }
            }


            if (event.getPackageName() != null && event.getPackageName().equals("com.android.settings")) {

                getService().performGlobalAction(GLOBAL_ACTION_BACK);
                sleepShort();
//                            gotoDeviceAdminPermissionSetting();
                return;
            }

            gotoSystemSettings();
            sleep();
        }

    }
}
