package com.grigowashere.aismap.ui;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.util.Log;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * Инкапсулирует проверку и запрос runtime-разрешений
 */
public class PermissionsBinder {

	private static final String TAG = "PermissionsBinder";
	private final Activity activity;

	public PermissionsBinder(Activity activity) {
		this.activity = activity;
	}

	public boolean ensurePermission(String permission, int requestCode) {
		if (ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED) {
			return true;
		}
		Log.d(TAG, "Requesting permission: " + permission);
		ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
		return false;
	}

	public boolean handleOnRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults, int expectedCode, Runnable onGranted, Runnable onDenied) {
		if (requestCode != expectedCode) return false;
		boolean granted = grantResults != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
		if (granted) {
			if (onGranted != null) onGranted.run();
		} else {
			if (onDenied != null) onDenied.run();
		}
		return true;
	}
}


