package com.foxx.androidcast;

/*********************************************************************
 * PermissionHelper.java
 * Created at: Fri 15 May 2026 16:49:02 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class PermissionHelper
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (5 commits, 171 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	3d735c673c6958e683b2771b55d77a646a66f63c121c5c7542293fb707bede5f
**********************************************************************/
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

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

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

/** Requests and explains runtime permissions for LAN cast. */
public final class PermissionHelper {
    public static final int REQUEST_CODE = 1001;
    public static final int REQUEST_RECEIVER_PLAYBACK = 1002;

    public static final class PermissionItem {
        public final String permission;
        public final String label;
        public final boolean required;

        PermissionItem(String permission, String label, boolean required) {
            this.permission = permission;
            this.label = label;
            this.required = required;
        }
    }

    private PermissionHelper() {}

    public static boolean hasAll(Activity activity) {
        return missing(activity, false).isEmpty();
    }

    public static boolean hasAllForAudio(Activity activity) {
        return missing(activity, true).isEmpty();
    }

    public static void request(Activity activity) {
        request(activity, false);
    }

    public static void requestForCast(Activity activity, boolean audioEnabled) {
        request(activity, audioEnabled);
    }

    /** Shows a dialog listing missing permissions; offers request or app settings. */
    public static void remindIfMissing(Activity activity, boolean includeAudio) {
        List<PermissionItem> missing = describeMissing(activity, includeAudio);
        if (missing.isEmpty()) {
            return;
        }
        StringBuilder body = new StringBuilder();
        for (PermissionItem item : missing) {
            body.append("• ").append(item.label);
            body.append(item.required ? " (required)\n" : " (recommended)\n");
        }
        new AlertDialog.Builder(activity)
                .setTitle(R.string.permissions_missing_title)
                .setMessage(body.toString().trim())
                .setPositiveButton(R.string.permissions_grant, (d, w) ->
                        ActivityCompat.requestPermissions(activity,
                                permissionsOnly(missing), REQUEST_CODE))
                .setNeutralButton(R.string.permissions_app_settings, (d, w) -> openAppSettings(activity))
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }

    private static void request(Activity activity, boolean includeAudio) {
        List<String> missing = missing(activity, includeAudio);
        if (!missing.isEmpty()) {
            ActivityCompat.requestPermissions(
                    activity, missing.toArray(new String[0]), REQUEST_CODE);
        }
    }

    private static List<String> missing(Activity activity, boolean includeAudio) {
        List<PermissionItem> items = describeMissing(activity, includeAudio);
        List<String> perms = new ArrayList<>();
        for (PermissionItem item : items) {
            perms.add(item.permission);
        }
        return perms;
    }

    private static List<PermissionItem> describeMissing(Activity activity, boolean includeAudio) {
        List<PermissionItem> needed = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                needed.add(new PermissionItem(Manifest.permission.POST_NOTIFICATIONS,
                        "Notifications (cast status)", true));
            }
        }
        if (includeAudio && PlatformCastSupport.isAudioCaptureSupported()) {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                needed.add(new PermissionItem(Manifest.permission.RECORD_AUDIO,
                        "Microphone (fallback when no app audio)", false));
            }
        }
        return needed;
    }

    private static String[] permissionsOnly(List<PermissionItem> items) {
        String[] arr = new String[items.size()];
        for (int i = 0; i < items.size(); i++) {
            arr[i] = items.get(i).permission;
        }
        return arr;
    }

    public static void openAppSettings(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        activity.startActivity(intent);
    }

    /** Permissions needed before receiver cast / PiP (notifications for foreground service). */
    public static boolean hasReceiverPlaybackReady(android.content.Context context) {
        return missingForReceiverPlayback(context).isEmpty();
    }

    public static void remindForReceiverPlayback(Activity activity) {
        List<PermissionItem> missing = missingForReceiverPlayback(activity);
        if (missing.isEmpty()) {
            return;
        }
        StringBuilder body = new StringBuilder(activity.getString(R.string.pip_permissions_hint));
        body.append("\n\n");
        for (PermissionItem item : missing) {
            body.append("• ").append(item.label).append('\n');
        }
        new AlertDialog.Builder(activity)
                .setTitle(R.string.permissions_missing_title)
                .setMessage(body.toString().trim())
                .setPositiveButton(R.string.permissions_grant, (d, w) ->
                        ActivityCompat.requestPermissions(activity,
                                permissionsOnly(missing), REQUEST_RECEIVER_PLAYBACK))
                .setNeutralButton(R.string.permissions_app_settings, (d, w) -> openAppSettings(activity))
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }

    private static List<PermissionItem> missingForReceiverPlayback(android.content.Context context) {
        List<PermissionItem> needed = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                String label = context instanceof Activity
                        ? ((Activity) context).getString(R.string.permission_notifications_cast)
                        : "Notifications (cast status)";
                needed.add(new PermissionItem(Manifest.permission.POST_NOTIFICATIONS, label, true));
            }
        }
        return needed;
    }
}
