package com.dankal.dankal_launcher;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
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 java.util.ArrayList;
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;
    private boolean isA = false;

    @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("com.tencent.weread");
                managementInfo.setLock(ColumnDef.LockApp.UNLOCKED);
                if (isA) {
                    isA = false;
                    managementInfo.setUseType(ColumnDef.AppUseType.GAME_LOCK_TYPE);
                } else {
                    isA = true;
                    managementInfo.setUseType(ColumnDef.AppUseType.SAFE_TYPE);
                }

                LauncherManager.getInstance().addPackageInfo(managementInfo);

                //handler.sendEmptyMessageDelayed(1, 500);

            /*    ManagementInfo managementInfo2 = new ManagementInfo();
                managementInfo2.setUseEndTimeStamp(3600);
                managementInfo2.setPackageName("com.android.browser");
                managementInfo2.setLock(ColumnDef.LockApp.UNLOCKED);
              *//*  if (isA) {
                    isA = false;
                    managementInfo2.setUseType(ColumnDef.AppUseType.SAFE_TYPE);
                } else {
                    isA = true;
                    managementInfo2.setUseType(ColumnDef.AppUseType.LEARN_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));
        regions.add(Long.valueOf(3600));

        regions.add(Long.valueOf(3600));
        regions.add(Long.valueOf(7200));

        regions.add(Long.valueOf(28800));
        regions.add(Long.valueOf(32400));

        regions.add(Long.valueOf(32400));
        regions.add(Long.valueOf(36000));

        regions.add(Long.valueOf(36000 ));
        regions.add(Long.valueOf(39600 ));

        regions.add(Long.valueOf( 39600));
        regions.add(Long.valueOf(43200));

        regions.add(Long.valueOf(43200 ));
        regions.add(Long.valueOf(46800 ));

        regions.add(Long.valueOf( 46800));
        regions.add(Long.valueOf( 50400));

        regions.add(Long.valueOf(50400 ));
        regions.add(Long.valueOf(54000 ));

        regions.add(Long.valueOf( 54000));
        regions.add(Long.valueOf( 57600));

        regions.add(Long.valueOf(57600 ));
        regions.add(Long.valueOf(61200 ));

        regions.add(Long.valueOf( 61200));
        regions.add(Long.valueOf(64800));

        regions.add(Long.valueOf(64800 ));
        regions.add(Long.valueOf(68400 ));

        regions.add(Long.valueOf( 68400));
        regions.add(Long.valueOf( 72000));

        regions.add(Long.valueOf(72000 ));
        regions.add(Long.valueOf(75600 ));

        regions.add(Long.valueOf(75600));
        regions.add(Long.valueOf( 79200));

        regions.add(Long.valueOf(79200 ));
        regions.add(Long.valueOf(82800));


        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);*/

        //initTime();
//        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 initTime() {
        AppTimeBeanTow appTimeBean = (AppTimeBeanTow) JSONObject.parse(getString(R.string.abc));
        List<Long> regions = new ArrayList<>();
        if (appTimeBean.getList() != null && appTimeBean.getList().getList() != null) {
            for (int i = 0; i < appTimeBean.getList().getList().size(); i++) {
                if (appTimeBean.getList().getList().get(i).equals("1")) {
                    regions.add((long) (i * 3600));//起始时间 9*3600=当天的早上九点
                    regions.add((long) ((i + 1) * 3600));//结束时间
                }
            }
        }
        int mode;
        mode = ColumnDef.TimeManager.WORK_DAY;


        //设置管控配置
        TimeConfig config = new TimeConfig.Builder(mode) //管控类型 WORK_DAY=工作日 WEEK_RESET=周末 HOLIDAY_MODE=假日
                .lockScreenMode(ColumnDef.LockScreen.MODE_REST) //指定不包含regions的时间段中的锁屏模式
                .addUseRegion(regions) //用户可使用的时间段
                .addAppTypeConfig(ColumnDef.AppUseType.GAME_LOCK_TYPE,
                        46800
                )
                //指定某一类别的app每天可使用的最大时长
                .build();
        //添加管控配置
        LauncherManager.getInstance().addWorkMode(config);
        //设置当前的工作模式（主要是针对假日模式，其他两个模式会根据当前时间自动变换，
        //在假日模式过期之后需要主动调用此方法设置为其他模式）

        LauncherManager.getInstance().setCurrentWorkMode(mode);
    }

    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");
    }
}
