package com.cloudflare.realtimekit;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.content.pm.ServiceInfo;
import android.app.Activity;
import android.widget.Toast;
import com.cloudflare.realtimekit.RTKHolder;

public class ForegroundService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        if (action != null) {
            if (action.equals(Constants.ACTION_FOREGROUND_SERVICE_START)) {
                if(RTKHolder.currActivity!=null) {
                    NotificationHelper notificationHelper = NotificationHelper.getInstance(RTKHolder.currActivity);
                    Notification notification = notificationHelper.buildNotification(RTKHolder.currActivity);
                    if (notification != null) {
                        try {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                startForeground(notificationHelper.NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
                            } else {
                                startForeground(notificationHelper.NOTIFICATION_ID, notification);
                            }
                        } catch (RuntimeException e) {
                            RTKLogger.w("ForegroundService", "Failed to start ForegroundService due to: " + e.getMessage());
                        }
                    }
                }

            } else if (action.equals(Constants.ACTION_FOREGROUND_SERVICE_STOP)) {
                stopSelf();
            }
        }
        return START_NOT_STICKY;

    }
}
