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

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
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

class AlarmViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: AlarmRepository
    private val scheduler: AlarmScheduler

    init {
        val alarmDao = AlarmDatabase.getDatabase(application).alarmDao()
        repository = AlarmRepository(alarmDao)
        scheduler = AlarmScheduler(application)
    }

    var allAlarms = repository.allAlarms.asLiveData()

    fun insert(alarm: Alarm) = viewModelScope.launch {
        val insertedUser = repository.insert(alarm)
        if (insertedUser.isEnabled) {
            scheduler.setAlarm(insertedUser)
        }
    }

    fun update(alarm: Alarm) = viewModelScope.launch {
        repository.update(alarm)
        scheduler.cancelAlarm(alarm)

        if (alarm.isEnabled) {
            scheduler.setAlarm(alarm)
        }
    }

    fun delete(alarm: Alarm) = viewModelScope.launch {
        repository.delete(alarm)
        scheduler.cancelAlarm(alarm)
    }

    fun truncate() = viewModelScope.launch {
        repository.truncate()
    }

    fun getAlarmById(id: Int): LiveData<Alarm> {
        return repository.getAlarmById(id)
    }
}
