package com.jkanetwork.st.frasesdeanime

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.app.PendingIntent
import java.util.Calendar
import android.app.AlarmManager
import android.util.Log
import android.app.Notification
import android.app.NotificationManager

/**
 * Created by kprkpr on 18/07/17.
 * Here, functions for using in every part of app
 */


/** Restart activity without doing animations for refresh favs
 * @param act: Use "this.intent"
 * */
fun restartActivity(act: AppCompatActivity){
    val intent = act.intent
    act.overridePendingTransition(0, 0)
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
    act.finish()
    act.overridePendingTransition(0, 0)
    act.startActivity(intent)
}


/* Call for putting alarm */
fun putAlarm(context: Context) {
    var P = Prefs(context)
    //val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    /* Common vars for alarm config */
    val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val sender = PendingIntent.getBroadcast(context, 1, Intent(context, AlarmNotif::class.java), 0)

    /* Cancel alarm first */
    alarmMgr.cancel(sender)
    //nm.cancel(1);


    var time = Calendar.getInstance()
    if (P.getNotifOn()) {
        if (P.getPersNotifOn()) { /* Persistent */
            var intent = Intent()
            intent.setAction("com.jkanetwork.st.frasesdeanime.notif")
            context.sendBroadcast(intent)

        }else{ /* At x hour every day */

            /* Here set the alarm to one time a day in selected date. Default: 8AM */
            /* Shedechule Alarm for tomorrow instead before now if alarm set to before. */
            if (time.get(Calendar.HOUR_OF_DAY) > P.getHour() || ( time.get(Calendar.HOUR_OF_DAY) == P.getHour() && time.get(Calendar.MINUTE) > P.getMinute())) {
                /* Add a day */
                time.add(Calendar.DATE, 1)
            }

            time.set(Calendar.HOUR_OF_DAY, P.getHour())
            time.set(Calendar.MINUTE, P.getMinute())
            time.set(Calendar.SECOND, 0)
            Log.d("STLOG (Next)", time.getTime().toString())
            alarmMgr.setRepeating(AlarmManager.RTC, time.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender) // Repeat every day
        }


    }
}


class App : Application() {

    companion object {

    }

    override fun onCreate() {
        super.onCreate()
    }
}