package com.secspace.lib.common.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.provider.Telephony;
import android.support.v4.app.NotificationManagerCompat;
import android.telecom.TelecomManager;
import android.text.TextUtils;
import android.util.Log;

import com.secspace.lib.common.compat.BuildCompat;
import com.secspace.lib.common.env.Packages;

import java.lang.reflect.Method;
import java.util.Set;

import static android.content.Context.POWER_SERVICE;


/**
 * Created by cyw_m on 2018/4/28.
 */

public class SettingsUtil {
    private static final String TAG = "SettingsUtil";

    public static void startOriginAppDetail(Context context, String packageName) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", packageName, null));
        context.startActivity(intent);
    }

    /**
     * 跳转到在上层应用显示
     *
     * @param ctx
     */
    public static void startOverlay(Context ctx) {
        Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + ctx.getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        ctx.startActivity(intent);
    }


    /**
     * 请求系统设置权限
     *
     * @param ctx
     */
    public static void requestWriteSettings(Context ctx) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
        intent.setData(Uri.parse("package:" + ctx.getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(intent);
    }

    public static boolean isNotificationCenterEnabled(Context ctx) {
        Set<String> enabledListenerPackages = NotificationManagerCompat.getEnabledListenerPackages(ctx);
        if (enabledListenerPackages.contains(ctx.getPackageName()))
            return true;
        return false;
    }


    /**
     * 重新开启MyNotificationListenerService
     */
    public static void toggleNotificationCenter(Context ctx, Class clazz) {
        ComponentName thisComponent = new ComponentName(ctx, clazz);
        PackageManager pm = ctx.getPackageManager();
        pm.setComponentEnabledSetting(thisComponent, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(thisComponent, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
        Log.i(TAG, "toggle: reset notificationlistener enabled");
    }

    /**
     * 跳转到通知管理激活页面
     */
    public static void activeNotificationCenter(Activity act) {
        act.startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS));
    }

    public static void startAppStartManager(Activity act) {
        if (!BuildCompat.isEMUI()) {
            return;
        }
        Intent intent = new Intent();
        intent.setPackage(Packages.PkgHuaWei.PACKAGENAME_HW_SYSTEM_MANAGER);
        intent.setComponent(Packages.CompHuaWei.COMPONENTNAME_HW_SYSTEM_MANAGER_START);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        act.startActivity(intent);
    }

    public static void startMainScreenActivity(Activity act) {
        if (!BuildCompat.isEMUI()) {
            return;
        }
        Intent intent = new Intent();
        intent.setPackage(Packages.PkgHuaWei.PACKAGENAME_HW_SYSTEM_MANAGER);
        intent.setComponent(Packages.CompHuaWei.COMPONENTNAME_HW_SYSTEM_MANAGER_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        act.startActivity(intent);
    }

    public static void ignoreBatteryOptimization(Activity activity, String packageName) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            activity.startActivity(intent);
        }
    }

    public static boolean isIgnoreBatteryOptimization(Context context, String packageName) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
            return powerManager.isIgnoringBatteryOptimizations(packageName);
        }
        return true;
    }

    /**
     * 是否是默认短信
     *
     * @param ctx
     * @param packageName
     * @return
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean isDefaultSms(Context ctx, String packageName) {
        if (TextUtils.equals(Telephony.Sms.getDefaultSmsPackage(ctx), packageName)) {
            return true;
        }
        return false;
    }


    /**
     * 设置成默认短信应用
     *
     * @param ctx
     * @param packageName
     */
    public static void setDefaultSMS(Context ctx, String packageName) {
        Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
        intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(intent);
    }

    /**
     * 设置默认的电话应用
     */
    @TargetApi(Build.VERSION_CODES.M)
    @SuppressLint("PrivateApi")
    public static void setDefaultDialer(Context context, String packageName) {
        try {
            TelecomManager tm = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
            if (tm != null) {
                Method m = tm.getClass().getDeclaredMethod("setDefaultDialer", String.class);
                m.invoke(tm, packageName);
                packageName = tm.getDefaultDialerPackage();
                DebugLog.d(TAG, "defaultDialer: " + packageName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否是默认桌面
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isDefaultLauncher(Context context, String packageName) {
        ResolveInfo resolveInfo = PkgManager.getInstance(context).queryDefaultLauncher();
        if (resolveInfo != null && TextUtils.equals(resolveInfo.activityInfo.packageName, packageName)) {
            return true;
        }
        return false;
    }

    public static void switchDefaultPayment(Context act, ComponentName componentName){
        Intent intent = new Intent("android.nfc.cardemulation.action.ACTION_CHANGE_DEFAULT");
        intent.putExtra("component", componentName);
        intent.putExtra("category", "payment");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        act.startActivity(intent);
    }

    public static boolean isGrantedUsagePremission(Context context) {
        boolean granted = false;
        AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.getPackageName());
        if (mode == AppOpsManager.MODE_DEFAULT) {
            granted = (context.checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
        } else {
            granted = (mode == AppOpsManager.MODE_ALLOWED);
        }
        return granted;
    }

    public static void screenOn(Context context) {
        PowerManager mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (mPowerManager != null) {
            @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
            mWakeLock.acquire(10 * 60 * 1000L /*10 minutes*/);
            mWakeLock.release();
        }
    }
}
