package com.foxx.androidcast;

/*********************************************************************
 * PictureInPictureHelper.java
 * Created at: Mon 18 May 2026 17:35:14 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class PictureInPictureHelper
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (3 commits, 109 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	d3227a4c9a0c426a1b82d17b36a16927cf4534dbd7e10553e6804b583ee8e161
**********************************************************************/
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Rational;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import android.app.PictureInPictureParams;

/**
 * Picture-in-picture for receiver playback (API 26+). No runtime permission; user can disable PiP per app.
 */
public final class PictureInPictureHelper {
    private PictureInPictureHelper() {}

    public static boolean isSupported() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
    }

    /** Whether the app is allowed to enter PiP (system / user app-ops). */
    public static boolean isAllowedForApp(@NonNull Context context) {
        if (!isSupported()) {
            return false;
        }
        PackageManager pm = context.getPackageManager();
        if (!pm.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
            return false;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            if (appOps == null) {
                return true;
            }
            int mode = appOps.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE,
                    android.os.Process.myUid(), context.getPackageName());
            return mode == AppOpsManager.MODE_ALLOWED;
        }
        return true;
    }

    public static PictureInPictureParams buildParams(Context context, int videoWidth, int videoHeight) {
        PictureInPictureParams.Builder builder = new PictureInPictureParams.Builder()
                .setAspectRatio(aspectRatio(videoWidth, videoHeight));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            boolean allowed = isAllowedForApp(context);
            builder.setAutoEnterEnabled(allowed);
            builder.setSeamlessResizeEnabled(allowed);
        }
        return builder.build();
    }

    public static void applyParams(@NonNull Activity activity, int videoWidth, int videoHeight) {
        if (!isSupported()) {
            return;
        }
        activity.setPictureInPictureParams(buildParams(activity, videoWidth, videoHeight));
    }

    public static boolean enter(@NonNull Activity activity, int videoWidth, int videoHeight) {
        if (!isSupported() || !isAllowedForApp(activity)) {
            return false;
        }
        try {
            return activity.enterPictureInPictureMode(buildParams(activity, videoWidth, videoHeight));
        } catch (IllegalStateException e) {
            return false;
        }
    }

    public static void showEnableInSettingsDialog(@NonNull Activity activity) {
        new AlertDialog.Builder(activity)
                .setTitle(R.string.pip_disabled_title)
                .setMessage(R.string.pip_disabled_message)
                .setPositiveButton(R.string.permissions_app_settings, (d, w) -> openPipSettings(activity))
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }

    public static void openPipSettings(@NonNull Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent intent = new Intent("android.settings.APP_PICTURE_IN_PICTURE_SETTINGS",
                    Uri.fromParts("package", activity.getPackageName(), null));
            activity.startActivity(intent);
        } else {
            PermissionHelper.openAppSettings(activity);
        }
    }

    private static Rational aspectRatio(int width, int height) {
        if (width > 0 && height > 0) {
            return new Rational(width, height);
        }
        return new Rational(16, 9);
    }
}
