package com.dankal.dankal_launcher;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.widget.TextView;
import android.widget.Toast;

import com.android.launcher3.accessibility.DeviceReceiver;
import com.android.launcher3.accessibility.StopRunReceiver;
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.TimeConfig;
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.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import static com.android.launcher3.Launcher.APP_COPY_PACKAGE_NAME;
import static com.android.launcher3.manager.LauncherManager.getContext;

public class PackageManageActivity extends Activity {

    public static final String TAG = "PackageManageActivity";

    private TextView tvAdd, tvRemove;

    private TextView tvLock, tvUnlock;

    private KToast toast;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                  /*  List<Long> regions = new ArrayList<>();
                    regions.add(Long.valueOf(9 * 3600));
                    regions.add(Long.valueOf(10 * 3600));

                    regions.add(Long.valueOf(10 * 3600));
                    regions.add(Long.valueOf(11 * 3600));

                    regions.add(Long.valueOf(11 * 3600));
                    regions.add(Long.valueOf(12 * 3600));

                    regions.add(Long.valueOf(12 * 3600));
                    regions.add(Long.valueOf(13 * 3600));

                    regions.add(Long.valueOf(13 * 3600));
                    regions.add(Long.valueOf(14 * 3600));

                    regions.add(Long.valueOf(15 * 3600));
                    regions.add(Long.valueOf(17 * 3600));

                    TimeConfig config = new TimeConfig.Builder(ColumnDef.TimeManager.WORK_DAY)
                            .lockScreenMode(ColumnDef.LockScreen.MODE_REST)
                            .addUseRegion(regions)
                            .addAppTypeConfig(ColumnDef.AppUseType.GAME_LOCK_TYPE, 46800)
                            .build();
                    LauncherManager.getInstance().addWorkMode(config);*/
                    break;
                case 1:
//
                    ManagementInfo managementInfo = new ManagementInfo();
                    managementInfo.setUseEndTimeStamp(43320);

                    managementInfo.setPackageName("com.tencent.mobileqq");
                    managementInfo.setLock(ColumnDef.LockApp.LOCKED);
                    managementInfo.setUseType(ColumnDef.AppUseType.GAME_LOCK_TYPE);

                    LauncherManager.getInstance().addPackageInfo(managementInfo);
                    Logger.e(TAG, "AFTER\t" + LauncherManager.getInstance().getManageAppInfo("com.tencent.mobileqq").toString());
                    break;

                case 2:
                    ManagementInfo managementInfo1 = new ManagementInfo();
                    managementInfo1.setUseEndTimeStamp(43320);

                    managementInfo1.setPackageName("com.tencent.mobileqq");
                    managementInfo1.setLock(ColumnDef.LockApp.LOCKED);
                    managementInfo1.setUseType(ColumnDef.AppUseType.GAME_LOCK_TYPE);

                    LauncherManager.getInstance().addPackageInfo(managementInfo1);
                    break;
            }


//            LauncherManager.getInstance().setCurrentWorkMode(ColumnDef.TimeManager.WORK_DAY);
        }
    };

    private Context mContent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_package_manage);

        /*LauncherManager.getInstance().changeExitState(true);
        LauncherManager.getInstance().setInterceptSystemSetting(false);*/

        tvAdd = findViewById(R.id.tv_add);

        tvRemove = findViewById(R.id.tv_remove);

        tvLock = findViewById(R.id.tv_lock);

        tvUnlock = findViewById(R.id.tv_unlock);

        toast = new KToast(this.getApplicationContext());

        findViewById(R.id.tv_start_app).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LauncherManager.getInstance().backLauncherHome(getApplicationContext());
            }
        });

        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                List<Long> regions = new ArrayList<>();
//                regions.add(Long.valueOf(9 * 3600));
//                regions.add(Long.valueOf(10 * 3600));
//                TimeConfig config = new TimeConfig.Builder(ColumnDef.TimeManager.WORK_DAY)
//                        .lockScreenMode(ColumnDef.LockScreen.MODE_REST)
//                        .addUseRegion(regions)
//                        .addAppTypeConfig(ColumnDef.AppUseType.GAME_LOCK_TYPE, 60)
//                        .build();
//                LauncherManager.getInstance().addWorkMode(config);
//
//
//                LauncherManager.getInstance().setCurrentWorkMode(ColumnDef.TimeManager.WORK_DAY);

//                handler.sendEmptyMessageDelayed(2,2000);
                LauncherManager.getInstance().jumpDebugInfo(PackageManageActivity.this);
                //PermissionUtil.initLauncherIconIsShow(PackageManageActivity.this, false);
            }
        });

        findViewById(R.id.tv_is_user).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //LauncherManager.getInstance().jumpSearchAppCanUse(PackageManageActivity.this);

                /**
                 * 更新图标
                 */
             /*   Intent intent = new Intent();
                intent.setAction(Constants.ACTION_UPDATE_ICON);
                intent.putExtra(Constants.EXTRA_PACKAGE, "我是你爸爸");
                sendBroadcast(intent);*/

                Intent intent = new Intent(Constants.ACTION_UPDATE_ICON);
                intent.putExtra(Constants.EXTRA_PACKAGE, APP_COPY_PACKAGE_NAME);
                LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
            }
        });


        tvRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

// com.huawei.appmarket
//                managementInfo.setUseEndTimeStamp(30);
//
//                managementInfo.setPackageName("com.cubic.autohome");
//                managementInfo.setLock(ColumnDef.LockApp.DEADLINE);
//                managementInfo.setUseType(ColumnDef.AppUseType.GAME_LOCK_TYPE);
//
//                LauncherManager.getInstance().addPackageInfo(managementInfo);

                ManagementInfo managementInfo = new ManagementInfo();
                managementInfo.setUseEndTimeStamp(3600);
                managementInfo.setPackageName("cn.dankal.www.tudigong_partner");
                managementInfo.setLock(ColumnDef.LockApp.UNLOCKED);
                managementInfo.setUseType(ColumnDef.AppUseType.SAFE_TYPE);

                LauncherManager.getInstance().addPackageInfo(managementInfo);
                handler.sendEmptyMessageDelayed(1, 500);

                ManagementInfo managementInfo2 = new ManagementInfo();
                managementInfo2.setUseEndTimeStamp(3600);
                managementInfo2.setPackageName("com.huawei.appmarket");
                managementInfo2.setLock(ColumnDef.LockApp.UNLOCKED);
                managementInfo2.setUseType(ColumnDef.AppUseType.SAFE_TYPE);

                LauncherManager.getInstance().addPackageInfo(managementInfo2);
                handler.sendEmptyMessageDelayed(1, 500);
                // Logger.e(TAG, "before\t" + LauncherManager.getInstance().getManageAppInfo("com.tencent.mm").toString());


            }
        });


        tvLock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //LauncherManager.getInstance().forceLockScreenForever(PackageManageActivity.this);
                PermissionUtil.setDefaultL(getApplicationContext());
               /* handler.sendEmptyMessageDelayed(1,1000*15);
                PermissionUtil.setDefaultL(getApplicationContext());*/
                //LauncherManager.getInstance().jumpSearchAppCanUse(PackageManageActivity.this);

            }
        });

        tvUnlock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendEmptyMessageDelayed(2, 10000);
            }
        });

        findViewById(R.id.jump_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

//                        PermissionUtil.gotoBatteryOptimize(getApplicationContext());
                        LauncherManager.getInstance().changeExitState(true);
                        LauncherManager.getInstance().setInterceptSystemSetting(false);
                    }
                }).start();
            }
        });


        findViewById(R.id.tv_is_uninstall).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              /*  if (LauncherManager.getInstance().getUninstallEnable()){
                    Toast.makeText(PackageManageActivity.this, "可以卸载", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(PackageManageActivity.this, "不能卸载", Toast.LENGTH_SHORT).show();
                }*/

                /*Intent progressIntent = new Intent();
                progressIntent.setAction("activity.home.progress");
                progressIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(progressIntent);*/

                //LauncherManager.getInstance().getUninstallEnable()

               /* LauncherManager.getInstance().changeUninstallEnable(true);

                String msg = "辅助权限设置已开启，请根据提示点击，\n如无提示请等稍等 或 手动返回权限设置页面";
                toast.setText(msg);
                toast.show();
                toast.show();*/
                LauncherManager.getInstance().changeUninstallEnable(true);
            }
        });
        //findViewById(R.id.tv_is_uninstall).setOnLongClickListener();
        findViewById(R.id.tv_permission).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PackageManageActivity.this, PermissionSettingActivity.class));
            }
        });

        findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WindowPermissionCheck.openPermission(PackageManageActivity.this);
            }
        });

        findViewById(R.id.tv_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

              /*  ComponentName componentName = new ComponentName(PackageManageActivity.this, DeviceReceiver.class);
                DevicePolicyManager devicepolicymanager = (DevicePolicyManager) PackageManageActivity.this.getSystemService(Context.DEVICE_POLICY_SERVICE);
                if (devicepolicymanager != null && !devicepolicymanager.isAdminActive(componentName)) {
                    Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
                    intent.putExtra("android.app.extra.DEVICE_ADMIN", componentName);
                    startActivityForResult(intent, 1);
                }*/
            }
        });


//        Date date = new Date();
//
//        date.setTime(System.currentTimeMillis());
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(date);
//        int week = calendar.get(Calendar.DAY_OF_WEEK);
//
//        Logger.e(TAG, week + "\t" + (calendar.getFirstDayOfWeek() == Calendar.SUNDAY));
        List<Long> regions = new ArrayList<>();

        regions.add(Long.valueOf(0 * 3600));
        regions.add(Long.valueOf(12 * 3600));

        regions.add(Long.valueOf(14 * 3600));
        regions.add(Long.valueOf(15 * 3600 + (12 * 60)));

        regions.add(Long.valueOf(16 * 3600));
        regions.add(Long.valueOf(19 * 3600 ));

        TimeConfig config = new TimeConfig.Builder(ColumnDef.TimeManager.WORK_DAY)
                .lockScreenMode(ColumnDef.LockScreen.MODE_REST)
                .addUseRegion(regions)
                .addAppTypeConfig(ColumnDef.AppUseType.GAME_LOCK_TYPE, 46800)
                .build();
//
        LauncherManager.getInstance().addWorkMode(config);
        LauncherManager.getInstance().setCurrentWorkMode(ColumnDef.TimeManager.WORK_DAY);
//        handler.sendEmptyMessageDelayed(0, 15000);


        //判断是否有悬浮窗权限
        findViewById(R.id.tv_floating_window).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (WindowPermissionCheck.checkPermission(PackageManageActivity.this)) {
                    Toast.makeText(PackageManageActivity.this, "有悬浮窗权限", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(PackageManageActivity.this, "没有开启悬浮窗权限", Toast.LENGTH_SHORT).show();
                }
            }
        });

        findViewById(R.id.tv_change_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //隐藏图标
                //PermissionUtil.initLauncherIconIsShow(PackageManageActivity.this, false);
                // PermissionUtil.jumpStartInterface(PackageManageActivity.this);

                Intent intent = new Intent(Constants.ACTION_UPDATE_ICON);
                intent.putExtra(Constants.EXTRA_PACKAGE, APP_COPY_PACKAGE_NAME);
                LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
            }
        });
    }

    private void toggleNotificationListenerService() {
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(this, NotificationListener2.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(new ComponentName(this, NotificationListener2.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }

    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.i("zzzzzzzzzzz", "PackageManageActivity_onResume");

        Logger.e(TAG, PermissionUtil.hasOverLayerPermission(this) + "");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LauncherManager.getInstance().setInterceptSystemSetting(true);
        onResume();
    }

    public void showToastLongTow(String msg) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Logger.e(TAG, "showToastLong\t" + msg);
                toast.setText(msg);
                toast.show();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("zzzzzzzzzzz", "PackageManageActivity_onDestroy");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("zzzzzzzzzzz", "PackageManageActivity_onStop");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("zzzzzzzzzzz", "PackageManageActivity_onPause");
    }
}
