package com.foxx.androidcast.sender;

/*********************************************************************
 * SenderPreviewService.java
 * Created at: Tue 19 May 2026 12:23:39 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class SenderPreviewService
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 71 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	78df1d1f91b8baa1c9c4cb6344006edd47d13d1380a146ce7f450ca3fe87e913
**********************************************************************/
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.foxx.androidcast.CastNotifications;

/**
 * Foreground service so {@link SenderScreenPreview} can use MediaProjection on Android 10+.
 * Stopped when screen cast {@link ScreenCastService} starts (that service holds projection FGS).
 */
public final class SenderPreviewService extends Service {
    private static volatile boolean running;

    public static boolean isRunning() {
        return running;
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, SenderPreviewService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

    public static void stop(Context context) {
        context.stopService(new Intent(context, SenderPreviewService.class));
    }

    @Override
    public void onCreate() {
        super.onCreate();
        CastNotifications.createChannels(this);
        running = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(CastNotifications.ID_SENDER + 100,
                CastNotifications.sender(this, getString(com.foxx.androidcast.R.string.preview_screen_active),
                        SenderPreviewService.class));
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        running = false;
        stopForeground(STOP_FOREGROUND_REMOVE);
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
