package xyz.kusoft.tradebotmonitor

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import java.util.concurrent.Executors

object RetrainScheduler {
    private const val ACTION_RETRAIN = "xyz.kusoft.tradebotmonitor.RETRAIN"
    private const val REQUEST_CODE = 6406

    fun schedule(context: Context, hours: Int) {
        val interval = hours.coerceAtLeast(1) * 60L * 60L * 1000L
        val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        manager.setInexactRepeating(
            AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + interval,
            interval,
            pendingIntent(context),
        )
    }

    fun cancel(context: Context) {
        val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        manager.cancel(pendingIntent(context))
    }

    private fun pendingIntent(context: Context): PendingIntent =
        PendingIntent.getBroadcast(
            context,
            REQUEST_CODE,
            Intent(context, RetrainAlarmReceiver::class.java).setAction(ACTION_RETRAIN),
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
        )
}

class RetrainAlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val pending = goAsync()
        Executors.newSingleThreadExecutor().execute {
            try {
                val prefs = AppPrefs(context)
                if (prefs.retrainScheduleEnabled) {
                    TradeBotApi(prefs.apiBaseUrl, prefs.commandToken).requestRetrain()
                }
            } finally {
                pending.finish()
            }
        }
    }
}

class BootReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
        val prefs = AppPrefs(context)
        if (prefs.retrainScheduleEnabled) {
            RetrainScheduler.schedule(context, prefs.retrainIntervalHours)
        }
    }
}
