package kz.com.aman.kassa.bank.permissions;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;

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

public class PermissionsManagerImpl implements PermissionsManager {
    private static final int MY_PERMISSIONS_REQUEST = 107;
    private static final String[] PERMISSIONS_LIST = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private final Activity activity;
    private PermissionsCheckResultHandler permissionsCheckResultHandler;

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

    @Override
    public void checkPermissions(PermissionsCheckResultHandler permissionsCheckResultHandler) {
        for (String permission : PERMISSIONS_LIST) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                this.permissionsCheckResultHandler = permissionsCheckResultHandler;
                ActivityCompat.requestPermissions(activity, PERMISSIONS_LIST, MY_PERMISSIONS_REQUEST);
                return;
            }
        }

        permissionsCheckResultHandler.onPermissionsGranted();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST: {
                if (grantResults.length == PERMISSIONS_LIST.length) {
                    if (arePermissionsGranted(grantResults)) {
                        permissionsCheckResultHandler.onPermissionsGranted();
                    } else {
                        permissionsCheckResultHandler.onPermissionsDeclined();
                    }
                }
            }
        }
    }

    private boolean arePermissionsGranted(int[] grantResults) {
        boolean access = true;
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED)
                access = false;
        }
        return access;
    }
}
