package tech.starwin.utils.context_utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import io.reactivex.functions.Consumer;

/**
 * Created by SiKang on 2018/9/20.
 * 权限管理
 */
public class PermissionsHelper {

    /**
     * 需要在首页获取的主要权限
     */
    public static String[] MAIN_PERMISSIONS = new String[]{
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.READ_SMS,
            Manifest.permission.ACCESS_COARSE_LOCATION,//粗精度定位
            Manifest.permission.ACCESS_FINE_LOCATION,//卫星定位
            Manifest.permission.READ_PHONE_STATE
    };

    /**
     * 检查权限
     */
    public static void checkPermission(FragmentActivity activity, String[] permissions, final OnPermissionListener listener) {
        getPermission(new RxPermissions(activity), permissions, listener);
    }

    public static void checkPermission(Fragment fragment, String[] permissions, final OnPermissionListener listener) {
        getPermission(new RxPermissions(fragment), permissions, listener);
    }

    @SuppressLint("CheckResult")
    private static void getPermission(RxPermissions rxPermissions, final String[] permissions, final OnPermissionListener listener) {
        rxPermissions
                .requestEach(permissions)
                .subscribe(new Consumer<Permission>() {
                    int index = 0;
                    int refuseCount = 0;

                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            if (index == permissions.length - 1 && refuseCount == 0) {
                                listener.onAllow(permission, true);
                            } else {
                                listener.onAllow(permission, false);
                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            refuseCount++;
                            listener.onRefuse(permission);
                        } else {
                            refuseCount++;
                            listener.onRefuseAndNeverAskAgain(permission);
                        }
                        index++;
                    }
                });
    }

    /**
     * 去系统设置中设置权限
     */
    public static void goSystemSetting(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);

            localIntent.setClassName("com.android.settings",
                    "com.android.settings.InstalledAppDetails");

            localIntent.putExtra("com.android.settings.ApplicationPkgName",
                    context.getPackageName());
        }
        context.startActivity(localIntent);
    }

    /**
     * 是否开启了通知权限
     */
    @SuppressLint("NewApi")
    public static boolean isNotificationEnabled(Context context) {

        AppOpsManager mAppOps =
                (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);

        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass = null;

        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());

            Method checkOpNoThrowMethod =
                    appOpsClass.getMethod("checkOpNoThrow",
                            Integer.TYPE, Integer.TYPE, String.class);

            Field opPostNotificationValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION");
            int value = (Integer) opPostNotificationValue.get(Integer.class);

            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) ==
                    AppOpsManager.MODE_ALLOWED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public interface OnPermissionListener {
        /**
         * 允许权限
         */
        void onAllow(Permission permission, boolean allAllowed);

        /**
         * 拒绝权限，下次再问
         */
        void onRefuse(Permission permission);

        /**
         * 拒绝权限，且不要再问
         */
        void onRefuseAndNeverAskAgain(Permission permission);
    }

    public abstract static class OnSimplePermissionListener implements OnPermissionListener {
        @Override
        public void onRefuse(Permission permission) {

        }

        @Override
        public void onRefuseAndNeverAskAgain(Permission permission) {

        }
    }
}
