package com.jkanetwork.st.frasesdeanime

import android.app.Notification
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import java.util.Calendar
import android.app.AlarmManager
import androidx.core.app.NotificationCompat
import android.app.PendingIntent

/*
    Help of: https://github.com/okwrtdsh/AlarmTest/blob/master/app/src/main/kotlin/com/github/okwrtdsh/alarmtest/AlarmBroadcastReceiver.kt

 */

class AlarmNotif : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent?) {
        var db = SQLiteHelper(context)
        var P = Prefs(context)
        val time = Calendar.getInstance()
        var frase = db.getSentenceFromIDF(db.getIDFraseHoy())
        var anime = db.getAnimeFromIDF(db.getIDFraseHoy())
        val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

        nm.cancel(1);
        val notificationBuilder = NotificationCompat.Builder(context, "STN")
                .setContentTitle(anime)
                .setStyle(NotificationCompat.BigTextStyle().bigText(frase))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText(frase)
                .setWhen(System.currentTimeMillis())
                .setContentIntent(PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), 0))

        var noti = notificationBuilder.build();

        if (P.getPersNotifOn() == true) {
            noti.flags = Notification.FLAG_ONGOING_EVENT
        }

        nm.notify(1,noti);

        if (P.getPersNotifOn() == true) {
            /* Do notif change all days */
            time.add(Calendar.DATE, 1)
            time.set(Calendar.HOUR_OF_DAY, 0)
            time.set(Calendar.MINUTE, 0)
            time.set(Calendar.SECOND, 1)
            val sender = PendingIntent.getBroadcast(context, 1, Intent(context, AlarmNotif::class.java), 0)
            alarmMgr.setRepeating(AlarmManager.RTC, time.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender) // Repeat every day
        }else{ /* For boot actions */
            putAlarm(context)
        }
    }

}