package com.foxx.androidcast;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import androidx.annotation.Nullable;

/**
 * Holds the persistent tray notification so it cannot be swiped away
 * (non-FGS status notifications are dismissible on Android 13+).
 */
public class TrayForegroundService extends Service {
    private static final long HEARTBEAT_MS = 90_000L;

    private final Handler handler = new Handler(Looper.getMainLooper());
    private final Runnable heartbeat = new Runnable() {
        @Override
        public void run() {
            if (!CastTrayNotifier.shouldMaintainTray(TrayForegroundService.this)) {
                stopSelf();
                return;
            }
            CastTrayNotifier.startForegroundTray(TrayForegroundService.this);
            handler.postDelayed(this, HEARTBEAT_MS);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        CastTrayNotifier.startForegroundTray(this);
        handler.postDelayed(heartbeat, HEARTBEAT_MS);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!CastTrayNotifier.shouldMaintainTray(this)) {
            stopSelf();
            return START_NOT_STICKY;
        }
        CastTrayNotifier.startForegroundTray(this);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(heartbeat);
        stopForeground(STOP_FOREGROUND_REMOVE);
        super.onDestroy();
    }

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