package com.applemand.zmanim.feature.settings

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.applemand.zmanim.core.settings.SettingsRepository
import com.applemand.zmanim.core.settings.proto.HolidayFilters
import com.applemand.zmanim.core.settings.proto.Language
import com.applemand.zmanim.core.settings.proto.TempUnit
import com.applemand.zmanim.core.settings.proto.ThemeMode
import com.applemand.zmanim.core.settings.proto.UserSettings
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SettingsViewModel @Inject constructor(
    private val repo: SettingsRepository,
) : ViewModel() {

    val state: StateFlow<UserSettings?> = repo.settings
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)

    fun setLanguage(lang: Language) = viewModelScope.launch { repo.setUiLanguage(lang) }
    fun setThemeMode(mode: ThemeMode) = viewModelScope.launch { repo.setThemeMode(mode) }
    fun setTempUnit(unit: TempUnit) = viewModelScope.launch { repo.setTempUnit(unit) }
    fun setUseDynamicColor(on: Boolean) = viewModelScope.launch { repo.setUseDynamicColor(on) }
    fun setShowZmanim(on: Boolean) = viewModelScope.launch { repo.setShowZmanim(on) }
    fun setShowZmanimSeconds(on: Boolean) = viewModelScope.launch { repo.setShowZmanimSeconds(on) }
    fun setShowStatusBar(on: Boolean) = viewModelScope.launch { repo.setShowStatusBar(on) }
    fun setShowDafYomi(on: Boolean) = viewModelScope.launch { repo.setShowDafYomi(on) }
    fun setEnableNotifications(on: Boolean) = viewModelScope.launch { repo.setEnableNotifications(on) }
    fun setAutoSyncLocation(on: Boolean) = viewModelScope.launch { repo.setAutoSyncLocation(on) }
    fun setTwelveHourClock(on: Boolean) = viewModelScope.launch { repo.setTwelveHourClock(on) }
    fun setInIsrael(on: Boolean) = viewModelScope.launch { repo.setInIsrael(on) }
    fun setUseElevation(on: Boolean) = viewModelScope.launch { repo.setUseElevationForZmanim(on) }
    fun setCandleLightingMinutes(m: Int) = viewModelScope.launch { repo.setCandleLightingMinutes(m) }
    fun setHavdalahMinutes(m: Int) = viewModelScope.launch { repo.setHavdalahMinutes(m) }
    fun setSyncDays(d: Int) = viewModelScope.launch { repo.setSyncZmanimDays(d) }
    fun setHolidayFilters(yomTov: Boolean, fast: Boolean, minor: Boolean, roshChodesh: Boolean) =
        viewModelScope.launch {
            repo.setHolidayFilters(
                HolidayFilters.newBuilder()
                    .setYomTov(yomTov).setFast(fast).setMinor(minor).setRoshChodesh(roshChodesh)
                    .build()
            )
        }
    fun setZmanVisible(key: String, visible: Boolean) =
        viewModelScope.launch { repo.setZmanVisible(key, visible) }
}
