package top.yeij.cyrene.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import top.yeij.cyrene.domain.model.Device
import top.yeij.cyrene.domain.repository.IoTRepository

class IoTViewModel(
    private val ioTRepository: IoTRepository,
) : ViewModel() {

    val devices: StateFlow<List<Device>> = ioTRepository.getDevices()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())

    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error.asStateFlow()

    init {
        refreshDevices()
    }

    fun refreshDevices() {
        viewModelScope.launch {
            _isLoading.value = true
            ioTRepository.refreshDevices()
            _isLoading.value = false
        }
    }

    fun controlDevice(deviceId: String, action: String, value: Any? = null) {
        viewModelScope.launch {
            _isLoading.value = true
            _error.value = null
            ioTRepository.controlDevice(deviceId, action, value).fold(
                onSuccess = { },
                onFailure = { _error.value = it.message },
            )
            _isLoading.value = false
        }
    }

    fun togglePower(device: Device) {
        val action = if (device.state.power == true) "off" else "on"
        controlDevice(device.id, action)
    }

    fun clearError() {
        _error.value = null
    }
}
