package com.cloudsolutions.HMGPatientApp.PermissionManager;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;

public class HostNotificationPermissionManager {
    private static final int REQUEST_NOTIFICATION_PERMISSION = 100;


    /**
     * Checks if the notification permission is granted.
     *
     * @return true if the notification permission is granted, false otherwise.
     */
    public static boolean isNotificationPermissionGranted(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            try {
                return ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.POST_NOTIFICATIONS)
                        == PackageManager.PERMISSION_GRANTED;
            } catch (Exception e) {
                // Handle cases where the API is unavailable
                e.printStackTrace();
                return NotificationManagerCompat.from(activity).areNotificationsEnabled();
            }
        } else {
            // Permissions were not required below Android 13 for notifications
            return NotificationManagerCompat.from(activity).areNotificationsEnabled();
        }
    }

    /**
     * Requests the notification permission.
     */
    public static void requestNotificationPermission(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (!isNotificationPermissionGranted(activity)) {
                ActivityCompat.requestPermissions(activity,
                        new String[]{android.Manifest.permission.POST_NOTIFICATIONS},
                        REQUEST_NOTIFICATION_PERMISSION);
            }
        }
    }

    /**
     * Handles the result of the permission request.
     *
     * @param requestCode  The request code passed in requestPermissions().
     * @param permissions  The requested permissions.
     * @param grantResults The grant results for the corresponding permissions.
     */
    public static boolean handlePermissionResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            if (permissions.length > 0 &&
                    permissions[0].equals(android.Manifest.permission.POST_NOTIFICATIONS) &&
                    grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted
                System.out.println("Notification permission granted.");
                return true;
            } else {
                // Permission denied
                System.out.println("Notification permission denied.");
                return false;
            }

    }


}
