package it.integry.integrywmsnative.core.utility;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.widget.Toast;

import com.annimon.stream.Stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import it.integry.integrywmsnative.SplashActivity;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;

public class PermissionsHelper {

    public static void askPermissions(SplashActivity activity, Runnable onPermissionsConfirmed, RunnableArgs<Boolean> onPermissionsDenied) {

        List<String> permissionsToAsk = new ArrayList<>();
        permissionsToAsk.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissionsToAsk.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        //permissionsToAsk.add(Manifest.permission.INTERNET);
        //permissionsToAsk.add(Manifest.permission.ACCESS_WIFI_STATE);


        if(Build.VERSION.SDK_INT >= 23) {
            //permissionsToAsk.add(Manifest.permission.REQUEST_INSTALL_PACKAGES);
        }

        String[] permissionArray = new String[permissionsToAsk.size()];
        permissionsToAsk.toArray(permissionArray);




        activity.setOnRequestPermissionsResult((requestCode, permissions, grantResults) -> {
            switch (requestCode) {
                case 1: {

                    boolean allGranted = Stream.of(grantResults).allMatch(x -> x == PackageManager.PERMISSION_GRANTED);

                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.size() > 0 && allGranted) {

                        onPermissionsConfirmed.run();

                    } else {

                        boolean anyPermDeny = shouldShowRequestPermissionRationale( activity, permissions );

                        onPermissionsDenied.run(anyPermDeny);


                    }
                    return;
                }

                // other 'case' lines to check for other
                // permissions this app might request
            }
        });



        ActivityCompat.requestPermissions(activity, permissionArray,1);

    }

    private static boolean shouldShowRequestPermissionRationale(AppCompatActivity activity, String[] permissions) {
        boolean anyDeny = false;

        for(int i = 0; i < permissions.length && !anyDeny; i++) {
            if(!ActivityCompat.shouldShowRequestPermissionRationale(activity, permissions[i])) anyDeny = true;
        }

        return anyDeny;
    }

}
