package com.fq.channel.sdk.base.permission;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.fq.channel.sdk.base.interfaces.IPermissionRequestCallback;


/**
 * @Description: 权限处理
 * @Author: FLuty
 * @CreateDate: 2020/4/7 16:09
 */

public class PermissionManager {

    private static PermissionManager mPermissionInitManager;
    //权限授权申请提醒
    public static final int REQUEST_CODE = 101268;

    private IPermissionRequestCallback callback;
    private String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE};

    public static PermissionManager getInstance() {
        synchronized (PermissionManager.class) {
            if (null == mPermissionInitManager) {
                mPermissionInitManager = new PermissionManager();
            }
            return mPermissionInitManager;
        }
    }

    public void applyPermission(Context context, IPermissionRequestCallback callback) {
        this.callback = callback;
        if (Build.VERSION.SDK_INT < 23) {
            callback.onDone();
            return;
        }
        requestPermission(context);

    }

    private void requestPermission(Context context) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) context, permissions, REQUEST_CODE);
        } else {
            callback.onDone();
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (REQUEST_CODE == requestCode
                && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            callback.onDone();
        } else {
            callback.onDone();
        }
    }
}
