package eu.darken.bluemusic.devices.ui.settings

import dagger.hilt.android.lifecycle.HiltViewModel
import eu.darken.bluemusic.common.coroutine.DispatcherProvider
import eu.darken.bluemusic.common.datastore.value
import eu.darken.bluemusic.common.debug.logging.log
import eu.darken.bluemusic.common.debug.logging.logTag
import eu.darken.bluemusic.common.navigation.Nav
import eu.darken.bluemusic.common.navigation.NavigationController
import eu.darken.bluemusic.common.ui.ViewModel4
import eu.darken.bluemusic.common.upgrade.UpgradeRepo
import eu.darken.bluemusic.devices.core.DevicesSettings
import eu.darken.bluemusic.monitor.core.service.MonitorControl
import kotlinx.coroutines.flow.combine
import javax.inject.Inject

@HiltViewModel
class DevicesSettingsViewModel
@Inject
constructor(
    dispatcherProvider: DispatcherProvider,
    navCtrl: NavigationController,
    private val devicesSettings: DevicesSettings,
    private val monitorControl: MonitorControl,
    upgradeRepo: UpgradeRepo,
) : ViewModel4(dispatcherProvider, logTag("Settings", "Devices", "ViewModel"), navCtrl) {

    val state = combine(
        upgradeRepo.upgradeInfo,
        devicesSettings.isEnabled.flow,
        devicesSettings.restoreOnBoot.flow,
    ) { upgradeInfo, isEnabled, restoreOnBoot ->
        State(
            isUpgraded = upgradeInfo.isPro,
            isEnabled = isEnabled,
            restoreOnBoot = restoreOnBoot,
        )
    }.asStateFlow()

    fun upgrade() = launch {
        log(tag) { "upgrade()" }
        navTo(Nav.Main.Upgrade())
    }

    fun onToggleEnabled(enabled: Boolean) = launch {
        log(tag) { "onToggleEnabled($enabled)" }
        devicesSettings.setEnabled(enabled)
        // Disabling is handled centrally: MonitorControl observes enabledState and stops the
        // service; the orchestrator's own watcher tears down the session as a safety net.
        // forceStart: a quick disable->enable can race the old session's teardown — a plain
        // start would be swallowed by onStartCommand and killed by the old job's stopSelf.
        if (enabled) {
            monitorControl.startMonitor(forceStart = true)
        }
    }

    fun onToggleRestoreOnBoot(enabled: Boolean) = launch {
        log(tag) { "onToggleRestoreOnBoot($enabled)" }
        devicesSettings.restoreOnBoot.value(enabled)
    }


    data class State(
        val isUpgraded: Boolean,
        val isEnabled: Boolean,
        val restoreOnBoot: Boolean,
    )
}
