package com.cloudsolutions.HMGPatientApp.PermissionManager;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;

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

import com.peng.pennavmap.PlugAndPlaySDK;
import com.peng.pennavmap.R;
import com.peng.pennavmap.enums.InitializationErrorType;

/**
 * Manages background location permission requests and handling for the application.
 */
public class HostBgLocationManager {
    /**
     * Request code for background location permission
     */
    public static final int REQUEST_ACCESS_BACKGROUND_LOCATION_CODE = 301;

    /**
     * Request code for navigating to app settings
     */
    private static final int REQUEST_CODE_SETTINGS = 11234;

    /**
     * Alert dialog for denied permissions
     */
    private static AlertDialog deniedAlertDialog;

    /**
     * Checks if the background location permission has been granted.
     *
     * @param context the context of the application or activity
     * @return true if the permission is granted, false otherwise
     */

    public static boolean isLocationBackgroundGranted(Context context) {
        return ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * Requests the background location permission from the user.
     *
     * @param activity the activity from which the request is made
     */
    public static void requestLocationBackgroundPermission(Activity activity) {
        // Check if the ACCESS_BACKGROUND_LOCATION permission is already granted
        if (!isLocationBackgroundGranted(activity)) {
            // Permission is not granted, so request it
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION},
                    REQUEST_ACCESS_BACKGROUND_LOCATION_CODE);
        }
    }

    /**
     * Displays a dialog prompting the user to grant the background location permission.
     *
     * @param activity                       the activity where the dialog is displayed
     */
    public static void showLocationBackgroundPermission(Activity activity) {
        AlertDialog alertDialog = new AlertDialog.Builder(activity)
                .setCancelable(false)
                .setMessage(activity.getString(R.string.com_penguin_nav_ui_geofence_alert_msg))
                .setPositiveButton(activity.getString(R.string.com_penguin_nav_ui_go_to_settings), (dialog, which) -> {
                    if (activity.shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {
                        HostBgLocationManager.requestLocationBackgroundPermission(activity);
                    } else {
                        openAppSettings(activity);
                    }
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(activity.getString(R.string.com_penguin_nav_ui_later), (dialog, which) -> {
                    dialog.cancel();
                })
                .create();

        alertDialog.show();
    }

    /**
     * Handles the scenario where permissions are denied by the user.
     * Displays a dialog to guide the user to app settings or exit the activity.
     *
     * @param activity the activity where the dialog is displayed
     */
    public static synchronized void handlePermissionsDenied(Activity activity) {
        if (deniedAlertDialog != null && deniedAlertDialog.isShowing()) {
            deniedAlertDialog.dismiss();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setCancelable(false)
                .setMessage(activity.getString(R.string.com_penguin_nav_ui_permission_denied_dialog_msg))
                .setNegativeButton(activity.getString(R.string.com_penguin_nav_ui_cancel), (dialogInterface, i) -> {
                    if (PlugAndPlaySDK.externalPenNavUIDelegate != null) {
                        PlugAndPlaySDK.externalPenNavUIDelegate.onPenNavInitializationError(
                                InitializationErrorType.permissions.getTypeKey(),
                                InitializationErrorType.permissions);
                    }
                    activity.finish();
                })
                .setPositiveButton(activity.getString(R.string.com_penguin_nav_ui_go_settings), (dialogInterface, i) -> {
                    dialogInterface.dismiss();
                    openAppSettings(activity);
                });
        deniedAlertDialog = builder.create();
        deniedAlertDialog.show();
    }

    /**
     * Opens the application's settings screen to allow the user to modify permissions.
     *
     * @param activity the activity from which the settings screen is launched
     */
    private static void openAppSettings(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);

        if (intent.resolveActivity(activity.getPackageManager()) != null) {
            activity.startActivityForResult(intent, REQUEST_CODE_SETTINGS);
        }
    }
}
