package info.knacki.prometheusandroidexporter;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import info.knacki.prometheusandroidexporter.collector.DeviceCollector;
import info.knacki.prometheusandroidexporter.collector.MemoryCollector;
import info.knacki.prometheusandroidexporter.collector.PowerCollector;

public class MainService extends Service {
    public MainService() {
    }

    public static void StartService(Context ctx) {
        Intent i = new Intent(ctx, MainService.class);
        ctx.startService(i);
    }

    public static void StopService(Context ctx) {
        Intent i = new Intent(ctx, MainService.class);
        ctx.stopService(i);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
         return super.onStartCommand(intent, START_STICKY, startId);
    }

    @Override
    public void onCreate() {
        CollectorManager collectorManager = CollectorManager.GetInstance();
        collectorManager.tick(this);
        InitCollectors(collectorManager);
        ScheduleCollection();
        try {
            HttpService.Register(getApplicationContext());
        }
        catch (IOException e) {
            Logger.getLogger(MainService.class.getName()).log(Level.SEVERE, "Cannot start server: ", e);
        }
        NotifyIcon();
    }

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

    private void InitCollectors(CollectorManager manager) {
        //manager.RegisterCollector(new TestCollector());
        manager.RegisterCollector(new DeviceCollector());
        manager.RegisterCollector(new PowerCollector());
        manager.RegisterCollector(new MemoryCollector());
    }

    private void ScheduleCollection() {
        PeriodicWorkRequest job = new PeriodicWorkRequest.Builder(CollectorWorker.class, 15, TimeUnit.MINUTES).build();
        WorkManager.getInstance(this).enqueue(job);
    }

    private void NotifyIcon() {
        Notification notif = (new Notification.Builder(this)
            .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Prometheus Android Exporter")
            .setContentText("Service running")).build();
        notif.flags = Notification.FLAG_ONGOING_EVENT;
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(1, notif);
        startForeground(1, notif);
    }
}
