package com.example.shiftalarm

import android.content.Context
import java.time.LocalDate
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class ShiftRepository(private val context: Context) {
    private val db = AppDatabase.getDatabase(context)
    private val dao = db.shiftDao()

    suspend fun getShift(date: LocalDate, team: String, factory: String): String = withContext(Dispatchers.IO) {
        val override = dao.getOverride(factory, team, date.toString())
        if (override != null) {
            return@withContext override.shift
        }
        ShiftCalculator.getShift(date, team, factory)
    }

    suspend fun setOverride(date: LocalDate, shift: String, team: String, factory: String) {
        dao.insertOverride(ShiftOverride(factory, team, date.toString(), shift))
    }

    suspend fun clearOverride(date: LocalDate, team: String, factory: String) {
        dao.deleteOverride(factory, team, date.toString())
    }

    suspend fun getMemo(date: LocalDate): String? {
        return dao.getMemo(date.toString())?.content
    }

    suspend fun setMemo(date: LocalDate, content: String) {
        if (content.isEmpty()) {
            dao.deleteMemo(date.toString())
        } else {
            dao.insertMemo(DailyMemo(date.toString(), content))
        }
    }

    // Custom Alarms
    suspend fun getAllCustomAlarms(): List<CustomAlarm> = withContext(Dispatchers.IO) {
        dao.getAllCustomAlarms()
    }

    suspend fun addCustomAlarm(alarm: CustomAlarm): Long = withContext(Dispatchers.IO) {
        dao.insertCustomAlarm(alarm)
    }

    suspend fun updateCustomAlarm(alarm: CustomAlarm) = withContext(Dispatchers.IO) {
        dao.updateCustomAlarm(alarm)
    }

    suspend fun deleteCustomAlarm(alarm: CustomAlarm) = withContext(Dispatchers.IO) {
        dao.deleteCustomAlarm(alarm)
    }

    suspend fun clearAllCustomAlarms() = withContext(Dispatchers.IO) {
        dao.clearCustomAlarms()
    }
}
