package com.nadi.player.nativeplayer.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.widget.RemoteViews;

import com.nadi.player.MainActivity;
import com.nadi.player.R;
import com.nadi.player.nativeplayer.PlaybackService;

/**
 * Home-screen / TV launcher widget exposing Channel ▼ / Channel ▲ buttons.
 *
 * Each button fires a service intent the {@link PlaybackService} already
 * understands ({@code ACTION_ZAP_NEXT} / {@code ACTION_ZAP_PREV}) which
 * in turn routes through {@link com.nadi.player.nativeplayer.ChannelAwarePlayer}
 * — same fast-zap path the lock-screen ⏭ / ⏮ buttons use. So:
 *
 *   • Service running with channels loaded → channel switches instantly,
 *     no app reopen, video keeps playing.
 *   • Service not running → the no-op zap is harmless; tapping the
 *     widget body opens the Capacitor MainActivity, which displays the
 *     existing "Resume {channel}?" toast.
 *
 * Why no current-channel-name on the widget body? RemoteViews can't bind
 * to in-process singletons, so we'd need a {@code WidgetUpdateService}
 * to push channel changes every zap. That's a noticeable battery hit
 * for marginal UX gain — better deferred to a later iteration if users
 * actually ask for it.
 */
public final class ChannelWidgetProvider extends AppWidgetProvider {

    private static final int REQ_PREV = 1001;
    private static final int REQ_NEXT = 1002;
    private static final int REQ_OPEN = 1003;

    @Override
    public void onUpdate(Context ctx, AppWidgetManager mgr, int[] ids) {
        for (int id : ids) {
            mgr.updateAppWidget(id, buildRemoteViews(ctx));
        }
    }

    /** Public so the launcher can call us via {@code updateAppWidget(...)}
     *  in case we ever start pushing live channel name updates. */
    public static void refreshAll(Context ctx) {
        AppWidgetManager mgr = AppWidgetManager.getInstance(ctx);
        int[] ids = mgr.getAppWidgetIds(
                new ComponentName(ctx, ChannelWidgetProvider.class));
        if (ids == null || ids.length == 0) return;
        RemoteViews views = buildRemoteViews(ctx);
        for (int id : ids) mgr.updateAppWidget(id, views);
    }

    private static RemoteViews buildRemoteViews(Context ctx) {
        RemoteViews v = new RemoteViews(ctx.getPackageName(),
                R.layout.widget_channel);

        v.setOnClickPendingIntent(R.id.widget_btn_prev,
                zapPendingIntent(ctx, PlaybackService.ACTION_ZAP_PREV, REQ_PREV));
        v.setOnClickPendingIntent(R.id.widget_btn_next,
                zapPendingIntent(ctx, PlaybackService.ACTION_ZAP_NEXT, REQ_NEXT));
        v.setOnClickPendingIntent(R.id.widget_open_area,
                openAppPendingIntent(ctx));
        return v;
    }

    private static PendingIntent zapPendingIntent(Context ctx, String action,
                                                  int requestCode) {
        Intent i = new Intent(ctx, PlaybackService.class);
        i.setAction(action);
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= 23) flags |= PendingIntent.FLAG_IMMUTABLE;
        // PendingIntent.getForegroundService is API 26+; on API 24-25 we
        // fall back to getService which still delivers, just without the
        // foreground guarantee for cold-start widget taps.
        if (Build.VERSION.SDK_INT >= 26) {
            return PendingIntent.getForegroundService(ctx, requestCode, i, flags);
        }
        return PendingIntent.getService(ctx, requestCode, i, flags);
    }

    private static PendingIntent openAppPendingIntent(Context ctx) {
        Intent i = new Intent(ctx, MainActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= 23) flags |= PendingIntent.FLAG_IMMUTABLE;
        return PendingIntent.getActivity(ctx, REQ_OPEN, i, flags);
    }
}
