package kr.co.vividnext.sodalive.mypage.alarm.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.mypage.alarm.AlarmActivity
import kr.co.vividnext.sodalive.mypage.alarm.db.Alarm
import kr.co.vividnext.sodalive.mypage.alarm.db.AlarmDatabase
import kr.co.vividnext.sodalive.mypage.alarm.scheduler.AlarmScheduler
import java.util.Calendar

class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val alarmId = intent.getIntExtra(Constants.EXTRA_ALARM_ID, -1)

        if (alarmId > 0) {
            val alarmIntent = Intent(context, AlarmActivity::class.java).apply {
                putExtra(Constants.EXTRA_ALARM_ID, alarmId)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or
                    Intent.FLAG_ACTIVITY_CLEAR_TOP or
                    Intent.FLAG_ACTIVITY_SINGLE_TOP
            }

            val alarmDao = AlarmDatabase.getDatabase(context).alarmDao()
            val alarmLiveData = alarmDao.getAlarmById(alarmId)

            val observer = object : Observer<Alarm> {
                override fun onChanged(value: Alarm) {
                    val scheduler = AlarmScheduler(context)
                    if (value.days.isNotEmpty()) {
                        scheduler.setAlarm(value)
                    } else {
                        scheduler.cancelAlarm(value)

                        val calendar = Calendar.getInstance()
                        calendar.timeInMillis = value.time
                        calendar.add(Calendar.DAY_OF_YEAR, 1)

                        value.time = calendar.timeInMillis
                        value.isEnabled = false
                        CoroutineScope(Dispatchers.IO).launch {
                            alarmDao.updateAlarm(value)
                        }
                    }
                    alarmLiveData.removeObserver(this)
                }
            }

            CoroutineScope(Dispatchers.Main).launch {
                withContext(Dispatchers.Main) {
                    alarmLiveData.observeForever(observer)
                }
            }

            context.startActivity(alarmIntent)
        }
    }
}
