package com.android.launcher3.auto_get_permission.samsung;

import android.accessibilityservice.AccessibilityService;
import android.os.Build;
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 android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_HOME;
import static com.android.launcher3.auto_get_permission.AccessibilityNodeOperateUtil.getChildNodeByIdEqualText;
import static com.android.launcher3.auto_get_permission.AccessibilityNodeOperateUtil.getChildNodeEqual;

public class SamsungAutoPermissionGetter extends BaseAutoGetPermission {

    private static final String TAG = "SamsungAutoPermissionGetter";

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

    @Override
    public void requestkDeviceAdmin(AccessibilityEvent event) {
        AccessibilityNodeInfo sourceNode = event.getSource();
        if ("com.android.settings.Settings$DeviceAdminSettingsActivity".equals(event.getClassName().toString())) {
//                        已跳转到设备管理器页面


            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeEqual(sourceNode, appName);

            if (!performAction(accessibilityNodeInfo1, AccessibilityNodeInfo.ACTION_CLICK)) {
                showToastLong("请找到【" + appName + "】应用并点击");
                return;
            } else {
                sleepShort();
            }
            return;
        } else if ("com.android.settings.DeviceAdminAdd".equals(event.getClassName().toString())) {

            List<AccessibilityNodeInfo> nodeInfoList = sourceNode.findAccessibilityNodeInfosByViewId("com.android.settings:id/restricted_action");

            if (nodeInfoList != null && nodeInfoList.size() > 0 && nodeInfoList.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK)) {
                sleep();
                resetStep();
                return;
            } else {
                AccessibilityNodeInfo nodeInfo = getChildNodeEqual(sourceNode, "启动");
                if (performAction(nodeInfo, AccessibilityNodeInfo.ACTION_CLICK)) {
                    sleep();
                    resetStep();
                    return;
                }
                showToastLong("请点击【启用/激活此设备管理员】");
                return;
            }
        }

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

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

        if (event.getPackageName() == null) {
            gotoDeviceAdminPermissionSetting();
            sleep();
        }
//

    }

    @Override
    public void reqeustAutoStartUp(AccessibilityEvent event) {
        //                 三星   自动运行应用程序 -> 打开应用开关 -> 电池管理 -> 未监视的应用程序 -> 添加应用
        if ("com.samsung.android.sm.score.ui.ScoreBoardActivity".equals(event.getClassName().toString())) {
            AccessibilityNodeInfo sourceNode = event.getSource();
            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeEqual(sourceNode, "自动运行应用程序");
            if (accessibilityNodeInfo1 != null && accessibilityNodeInfo1.getParent() != null) {
                accessibilityNodeInfo1.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                sleep();
            }

        }

        if ("com.samsung.android.sm.autorun.ui.AutoRunActivity".equals(event.getClassName().toString())) {

            AccessibilityNodeInfo sourceNode = event.getSource();

            getChildNodeEqual(sourceNode, appName);
            AccessibilityNodeInfo frameLayoutNode = sourceNode.findAccessibilityNodeInfosByViewId("com.samsung.android.sm_cn:id/active_applications_detail").get(0).getParent().getParent();


//                            frameLayoutNode.getCollectionInfo()'

//                            for ()
//
            Logger.e(TAG, sourceNode.findAccessibilityNodeInfosByViewId("com.samsung.android.sm_cn:id/app_name").size() + "");
//
//                            Logger.e(TAG, "\t" + sourceNode.findAccessibilityNodeInfosByViewId("com.samsung.android.sm_cn:id/active_applications_detail").get(0).getParent().getChildCount());

//                            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeEqual(sourceNode, appName);
            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeByIdEqualText(sourceNode, "com.samsung.android.sm_cn:id/app_name", appName);


            accessibilityNodeInfo1.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
            sleep();
        }
    }

    @Override
    public void requestBatteryOptimize(AccessibilityEvent event) {
        AccessibilityNodeInfo sourceNode = event.getSource();
        //                 三星   自动运行应用程序 -> 打开应用开关 -> 电池管理 -> 未监视的应用程序 -> 添加应用
//                        if ("com.samsung.android.sm.score.ui.ScoreBoardActivity".equals(event.getClassName().toString())) {
//                            AccessibilityNodeInfo sourceNode = event.getSource();
//                            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeEqual(sourceNode, "自动运行应用程序");
//                            if (accessibilityNodeInfo1 != null && accessibilityNodeInfo1.getParent() != null) {
//                                accessibilityNodeInfo1.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
//                                sleep();
//                            }
//
//                        }
//
//                        if ("com.samsung.android.sm.autorun.ui.AutoRunActivity".equals(event.getClassName().toString())) {
//
//                            AccessibilityNodeInfo sourceNode = event.getSource();
//
//                            getChildNodeEqual(sourceNode, appName);
//                            AccessibilityNodeInfo frameLayoutNode = sourceNode.findAccessibilityNodeInfosByViewId("com.samsung.android.sm_cn:id/active_applications_detail").get(0).getParent().getParent();
//
//
////                            frameLayoutNode.getCollectionInfo()'
//
////                            for ()
////
//                            Logger.e(TAG, sourceNode.findAccessibilityNodeInfosByViewId("com.samsung.android.sm_cn:id/app_name").size() + "");
////
////                            Logger.e(TAG, "\t" + sourceNode.findAccessibilityNodeInfosByViewId("com.samsung.android.sm_cn:id/active_applications_detail").get(0).getParent().getChildCount());
//
////                            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeEqual(sourceNode, appName);
//                            AccessibilityNodeInfo accessibilityNodeInfo1 = getChildNodeByIdEqualText(sourceNode, "com.samsung.android.sm_cn:id/app_name", appName);
//
//
//                            accessibilityNodeInfo1.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
//                            sleep();
//                        }
    }

    @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".equals(event.getClassName())) {
            List<AccessibilityNodeInfo> recyclerViewListNode = sourceNode.findAccessibilityNodeInfosByViewId("com.android.settings:id/dashboard_container");
            if (recyclerViewListNode != null && recyclerViewListNode.size() > 0) {

                AccessibilityNodeInfo recyclerViewNode = recyclerViewListNode.get(0);

                AccessibilityNodeInfo developerChoiceNode = getChildNodeByIdEqualText(recyclerViewNode, "android:id/title", "开发者选项");
                long time = System.currentTimeMillis();
                while (developerChoiceNode == null && System.currentTimeMillis() - time < MAX_SEARCH_TIME) {

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

                    developerChoiceNode = getChildNodeByIdEqualText(recyclerViewNode, "android:id/title", "开发者选项");
                }
                if (performAction(developerChoiceNode, AccessibilityNodeInfo.ACTION_CLICK)) {
                    sleep();
                } else {
                    showToastLong("请点击【开发者选项】");
                    return;
                }

            }

        }

//                        三星不同版本之前的开发者选项的界面不一样 所以需要两种判断

        if ("com.android.settings.Settings$DevelopmentSettingsDashboardActivity".equals(event.getClassName())) {
            List<AccessibilityNodeInfo> listViewNodes = sourceNode.findAccessibilityNodeInfosByViewId("com.android.settings:id/list");
            if (listViewNodes != null && listViewNodes.size() > 0) {
                AccessibilityNodeInfo listViewNode = listViewNodes.get(0);
                AccessibilityNodeInfo usbNode = getChildNodeByIdEqualText(listViewNode, "android:id/title", "USB 调试");
                long time = System.currentTimeMillis();
                while (usbNode == null && System.currentTimeMillis() - time < MAX_SEARCH_TIME) {
                    if (listViewNode.isScrollable()) {
                        listViewNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                        sleepShort();
                        listViewNode.refresh();
                    } else {
                        break;
                    }
                    usbNode = getChildNodeByIdEqualText(listViewNode, "android:id/title", "USB 调试");
                }
                if (performAction(usbNode, AccessibilityNodeInfo.ACTION_CLICK)) {

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

            }
        }

        if ("com.android.settings.Settings$DevelopmentSettingsActivity".equals(event.getClassName())) {
            AccessibilityNodeInfo usbNode = getChildNodeEqual(sourceNode, "USB调试");
            if (!performAction(usbNode, AccessibilityNodeInfo.ACTION_CLICK)) {

                List<AccessibilityNodeInfo> listViewNodes = sourceNode.findAccessibilityNodeInfosByViewId("com.android.settings:id/list");
                if (listViewNodes != null && listViewNodes.size() > 0) {
                    AccessibilityNodeInfo listViewNode = listViewNodes.get(0);
                    usbNode = getChildNodeEqual(listViewNode, "USB调试");
                    long time = System.currentTimeMillis();
                    while (usbNode == null && System.currentTimeMillis() - time < MAX_SEARCH_TIME) {
                        if (listViewNode.isScrollable()) {
                            listViewNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                            sleepShort();
                            listViewNode.refresh();
                        } else {
                            break;
                        }
                        usbNode = getChildNodeEqual(listViewNode, "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.P) {

            if ("com.android.settings.applications.InstalledAppDetailsTop".equals(event.getClassName())) {
                boolean isTargetApp = getChildNodeEqual(nodeInfo, appName) != null;

                if (isTargetApp) {

                    List<AccessibilityNodeInfo> listViewNodes = nodeInfo.findAccessibilityNodeInfosByViewId("com.android.settings:id/list");
                    if (listViewNodes != null && !listViewNodes.isEmpty()) {

                        AccessibilityNodeInfo listViewNode = listViewNodes.get(0);


                        AccessibilityNodeInfo defaultLauncherNode = getChildNodeEqual(listViewNode, "主屏幕");


                        long time = System.currentTimeMillis();
                        while (defaultLauncherNode == null && System.currentTimeMillis() - time < MAX_SEARCH_TIME) {
                            if (listViewNode.isScrollable()) {
                                listViewNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                                listViewNode.refresh();
                                sleepShort();
                            } else {
                                break;
                            }
                            defaultLauncherNode = getChildNodeEqual(listViewNode, "主屏幕");
                        }

                        if (performAction(defaultLauncherNode, AccessibilityNodeInfo.ACTION_CLICK)) {
                            sleepShort();
                        } else {
                            showToastLong("请点击【主屏幕】");
                            return;
                        }
                    } else {
                        showToastLong("请点击【主屏幕】");
                    }

                    return;
                }
            }

            if ("com.android.settings.SubSettings".equals(event.getClassName()) && event.getText() != null && event.getText().toString().equals("[主屏幕]")) {

                AccessibilityNodeInfo accessibilityNodeInfo = getChildNodeEqual(nodeInfo, appName);

                if (performAction(accessibilityNodeInfo, AccessibilityNodeInfo.ACTION_CLICK)) {
                    sleepShort();
                    resetStep();
                    getService().performGlobalAction(GLOBAL_ACTION_HOME);
                } else {
                    showToastLong("请点击【" + appName + "】");
                    return;
                }

                return;
            }


            if ("android.app.Dialog".equals(event.getClassName()) && event.getText() != null && event.getText().toString().contains("选择您要使用的主屏幕")) {

                AccessibilityNodeInfo accessibilityNodeInfo = getChildNodeEqual(nodeInfo, appName);

                if (performAction(accessibilityNodeInfo, AccessibilityNodeInfo.ACTION_CLICK)) {
                    sleepShort();
                    resetStep();
                    getService().performGlobalAction(GLOBAL_ACTION_HOME);
                } else {
                    showToastLong("请点击【" + appName + "】");
                    return;
                }

                return;
            }

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

                getService().performGlobalAction(GLOBAL_ACTION_BACK);
                sleepShort();
//                            gotoDeviceAdminPermissionSetting();
                return;
            }
            gotoDefaultLauncherSetting();
            sleep();
        } else {
            if ("com.android.internal.app.ResolverActivity".equals(event.getClassName())) {
                AccessibilityNodeInfo targetAppNode = getChildNodeEqual(nodeInfo, appName);

                if (targetAppNode != null && targetAppNode.getParent() != null) {
                    targetAppNode.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    sleep();
                }

                List<AccessibilityNodeInfo> alwaysBtnList = nodeInfo.findAccessibilityNodeInfosByViewId("android:id/button_always");
                if (alwaysBtnList != null && alwaysBtnList.size() > 0 && performAction(alwaysBtnList.get(0), AccessibilityNodeInfo.ACTION_CLICK)) {

                } else {
                    showToastLong("请选择默认使用桌面为" + appName);
                    return;
                }

//                    AccessibilityNodeInfo alwaysBtn = getChildNodeByIdEqualText(nodeInfo, "android:id/button_always");
            }
        }
    }
}
