package com.bokecc.dwlivedemo.utils;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.app.Activity;
import java.lang.ref.WeakReference;

public class PermissionRequestBean {

    public PermissionRequestBean(String[] permissions) {
        this.permissions = permissions;
    }

    private String[] permissions;
    private WeakReference<Activity> weakReference;
    private PermissionCallback callback;

    public boolean hasPermission(Activity context) {
        return Permissions.has(context, permissions);
    }

    public void request(Activity context, PermissionCallback callback) {
        weakReference = new WeakReference<>(context);
        this.callback = callback;

        //没有权限有三种情况，一种是用户还没有授予过权限，需要去授予，二是用户上次点击了拒绝，本次依然询问，三是用户上次点击了拒绝并不再询问，此时需要提示去设置中打开权限才能使用功能
        if (!hasPermission(context)) {
            showPermission();
        } else {
            callback.onResult(true);
        }
    }

    public interface PermissionCallback {
        void onResult(boolean success);
    }

    private void showPermission() {
        if (weakReference != null && weakReference.get() != null) {
            Permissions.request(weakReference.get(), permissions, new Permissions.Consumer<Integer>() {
                @Override
                public void accept(Integer integer) {
                    if (weakReference != null && weakReference.get() != null) {
                        if (weakReference.get().isFinishing() || weakReference.get().isDestroyed()) {
                            return;
                        }
                        if (integer == PERMISSION_GRANTED) {
                            if (callback != null) {
                                callback.onResult(true);
                            }
                        } else {

                            if (callback != null) {
                                callback.onResult(false);
                            }
                        }
                    }

                }
            });
        }
    }
}