package com.grigowashere.aismap.services;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
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 androidx.core.app.NotificationCompat;

import com.grigowashere.aismap.MainActivity;
import com.grigowashere.aismap.R;

public class AISForegroundService extends Service {

	public static final String CHANNEL_ID = "aismap_foreground";
	private static final int NOTIFICATION_ID = 1001;

	@Override
	public void onCreate() {
		super.onCreate();
		createNotificationChannel();
		startForeground(NOTIFICATION_ID, buildNotification("Работа в фоне: обновление AIS/GPS"));
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// Здесь в дальнейшем запустим прием NMEA/UDP и GPS слушателей
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

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

	private void createNotificationChannel() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			NotificationChannel channel = new NotificationChannel(
					CHANNEL_ID,
					"AISMap Background",
					NotificationManager.IMPORTANCE_LOW
			);
			channel.setDescription("Фоновые обновления AIS и GPS");
			NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			if (nm != null) nm.createNotificationChannel(channel);
		}
	}

	private Notification buildNotification(String content) {
		Intent notificationIntent = new Intent(this, MainActivity.class);
		int flags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT : 0;
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, flags);
		return new NotificationCompat.Builder(this, CHANNEL_ID)
				.setContentTitle("AISMap")
				.setContentText(content)
                .setSmallIcon(R.mipmap.ic_launcher)
				.setContentIntent(pendingIntent)
				.setOngoing(true)
				.build();
	}
}


