package com.datarecovery.master.utils;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;

import androidx.activity.ComponentActivity;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;

import com.atmob.common.runtime.ContextUtil;

public class PermissionUtil {


    public static boolean hasFilePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return Environment.isExternalStorageManager();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return PermissionUtil.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        } else {
            return true;
        }
    }

    public static boolean hasPermission(String... permissions) {
        if (permissions == null) {
            return true;
        }
        Context context = ContextUtil.getContext();
        for (String permission : permissions) {
            boolean hasPermission = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
            if (!hasPermission) {
                return false;
            }
        }
        return true;
    }

    public static void requestWriteStoragePermission(ComponentActivity activity, PermissionCallback callback) {
        if (activity == null) {
            throw new RuntimeException("activity is null");
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            new ActivityForResultUtil<String, Boolean>().startActivityForResult(activity, new ActivityResultContracts.RequestPermission(), Manifest.permission.WRITE_EXTERNAL_STORAGE, result -> {
                if (result) {
                    if (callback != null) callback.onPermissionGranted();
                } else {
                    if (callback != null) callback.onPermissionDenied();
                }
            });
        } else {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            new ActivityForResultUtil<Intent, ActivityResult>().startActivityForResult(activity, new ActivityResultContracts.StartActivityForResult(), intent, result -> {
                if (Environment.isExternalStorageManager()) {
                    if (callback != null) callback.onPermissionGranted();
                } else {
                    if (callback != null) callback.onPermissionDenied();
                }
            });
        }
    }

    public interface PermissionCallback {
        void onPermissionGranted();

        void onPermissionDenied();
    }

}
