package com.android.launcher3.accessibility;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;
import android.widget.Toast;

import com.android.launcher3.auto_get_permission.BaseAutoGetPermission;
import com.android.launcher3.auto_get_permission.GeneralAutoGetPermission;
import com.android.launcher3.auto_get_permission.honor.HonorAutoPermissionGetter;
import com.android.launcher3.auto_get_permission.huawei.HuaweiAutoPermissionGetter;
import com.android.launcher3.auto_get_permission.meizu.MeizuAutoPermissionGetter;
import com.android.launcher3.auto_get_permission.nokia.NokiaAutoPermissionGetter;
import com.android.launcher3.auto_get_permission.oppo.OppoAutoPermissionGetter;
import com.android.launcher3.auto_get_permission.samsung.SamsungAutoPermissionGetter;
import com.android.launcher3.auto_get_permission.vivo.VivoAutoPermissionGetter;
import com.android.launcher3.auto_get_permission.xiaomi.XiaoMiAutoPermissionGetter;
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 java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * 自动开启权限
 */
public class PermissionOpenAccessiblityService extends AccessibilityService {

    private static final String TAG = "PermissionOpenAccessiblityService";
    private static final String TAG_TOW = "permission_show_info";

    private BaseAutoGetPermission permissionGetter;

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

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();

        if (SystemUtils.isHONOR()) {
            permissionGetter = new HonorAutoPermissionGetter(this);
        } else if (SystemUtils.isHW()) {
            permissionGetter = new HuaweiAutoPermissionGetter(this);
        } else if (SystemUtils.isMEIZU()) {
            permissionGetter = new MeizuAutoPermissionGetter(this);
        } else if (SystemUtils.isNOKIA()) {
            permissionGetter = new NokiaAutoPermissionGetter(this);
        } else if (SystemUtils.isOPPO()) {
            permissionGetter = new OppoAutoPermissionGetter(this);
        } else if (SystemUtils.isSAMSUNG()) {
            permissionGetter = new SamsungAutoPermissionGetter(this);
        } else if (SystemUtils.isVIVO()) {
            permissionGetter = new VivoAutoPermissionGetter(this);
        } else if (SystemUtils.isMIUI()) {
            permissionGetter = new XiaoMiAutoPermissionGetter(this);
        } else {
            permissionGetter = new GeneralAutoGetPermission(this);
        }


        LauncherManager.getInstance().changeExitState(true);
//        AccessibilityEvent accessibilityEvent = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
//        onAccessibilityEvent(accessibilityEvent);
        permissionGetter.start();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        permissionGetter.stop();
        return super.onUnbind(intent);
    }


    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        //监听魅族默认桌面选择

        Logger.e(TAG, "onAccessibilityEvent " + event.toString());


        AccessibilityNodeInfo rowNode = getRootInActiveWindow();//获取当前屏幕所有节点
        if (rowNode != null) {
            recycle(event, rowNode);
        }
        Log.i(TAG_TOW, "==============================================");


        if (LauncherManager.getInstance().isInterceptSystemSetting()) {
            return;
        }

        if (event == null || event.getClassName() == null) {
            return;
        }


        if ((event.getPackageName().toString().equals(getApplicationContext().getPackageName()) && !TextUtils.isEmpty(event.getClassName()) && event.getClassName().toString().equals("android.widget.LinearLayout"))) {
            Log.i("reqeustAutoStartUp", "GLOBAL_ACTION_BACK==返回");
            performGlobalAction(GLOBAL_ACTION_BACK);
            return;
        }


        Log.i("reqeustAutoStartUp", "event.getEventType()" + event.getEventType());

        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {

            permissionGetter.operateAccessibilityEvent(event);

        }

      /*  if (SystemUtils.isMEIZU()) {//处理魅族桌面
            handlerMeizhuDefaultDesktop(event);
        }*/

    }

    private boolean mIsSelectDefaultUse = false;

    private void handlerMeizhuDefaultDesktop(AccessibilityEvent event) {
        //点击事件
        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_CLICKED) {
            AccessibilityNodeInfo rowNode = event.getSource();
            //先判断，默认使用改应用是否勾选
            List<AccessibilityNodeInfo> selectViews = rowNode.findAccessibilityNodeInfosByText("默认使用该应用");
            if (selectViews != null && selectViews.size() > 0) {
                AccessibilityNodeInfo selectView = selectViews.get(0);
                if (selectView.isChecked()) {
                    mIsSelectDefaultUse = true;
                }
            }
            if (mIsSelectDefaultUse) {
                AccessibilityNodeInfo nodeInfo = event.getSource();
                if (nodeInfo.getText().equals("倍知守护孩子端")) {
                    Log.i("zzzzzzzzzzzzzzzzzzzz", "默认桌面设置成功");
                    PermissionUtil.mIsDefaultDesktop = true;
                    mIsSelectDefaultUse = false;
                }
            }
        }
    }

    @Override
    public void onInterrupt() {

    }


    /**
     * 权限完成后的操作 此处无法使用当前的context去startActivity
     */
    public void finish() {

    }

    @Override
    public void onDestroy() {
        permissionGetter.stop();
        super.onDestroy();
    }

    public void recycle(AccessibilityEvent event, AccessibilityNodeInfo info) {
        if (info.getChildCount() == 0) {
            Log.i(TAG_TOW, "child widget----------------------------" + info.getClassName());
            Log.i(TAG_TOW, "showDialog:" + info.canOpenPopup());
            Log.i(TAG_TOW, "Text：" + info.getText());
            Log.i(TAG_TOW, "windowId:" + info.getWindowId());
        } else {
            for (int i = 0; i < info.getChildCount(); i++) {
                if (info.getChild(i) != null) {
                    recycle(event, info.getChild(i));
                }
            }
        }

        try {
            Log.i("reqeustAutoStartUp", "当前界面包名：" + event.getPackageName() + "\n当前应用的包名：" + getApplicationContext().getPackageName());
            Log.i("reqeustAutoStartUp", "当前界面类名：" + event.getClassName() + "\n当前应用类：" + "android.widget.LinearLayout");


            //判断当前界面
            if (event.getPackageName().equals("android")) {
                Log.i("qqqqqqqqqqqqqqqqqqqq", "在系统界面");
                PermissionUtil.isSystemUI = true;
            } else {
                PermissionUtil.isSystemUI = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            PermissionUtil.isSystemUI = false;
        }
    }

}
