package com.ardrawing.ardrawingspace.util;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public final class PermissionTool {
    private PermissionTool() {
        // 防止实例化
    }

    private static final boolean IS_DEBUG = false;

    public static boolean hasPermission(Activity activity, String[] permissions) {
        if (isInvalidInput(activity, permissions)) return false;

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public static void reqPermission(Activity activity, String[] permissions, int requestCode) {
        if (isValidInput(activity, permissions)) {
            ActivityCompat.requestPermissions(activity, permissions, requestCode);
        }
    }

    public static boolean gotPermission(int[] grantResults) {
        if (grantResults == null || grantResults.length == 0) return false;

        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public static String[] getPermission() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
                ? new String[]{Manifest.permission.READ_MEDIA_IMAGES}
                : new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    }

    private static boolean isInvalidInput(Activity activity, String[] permissions) {
        return activity == null || permissions == null;
    }

    private static boolean isValidInput(Activity activity, String[] permissions) {
        if (IS_DEBUG) {
            Log.d("PermissionUtil", "Validating input");
        }
        return activity != null && permissions != null;
    }
}