package com.laseroptek.raman.ui.screens.info

import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import timber.log.Timber
import javax.inject.Inject

// An enum to clearly identify each line, making the code type-safe.
enum class ChartLine {
    INT_TEMP, EXT_TEMP, INT_HUMIDITY, EXT_HUMIDITY,
    KTP, CHAMBER1, CHAMBER2, BASE_PLATE, WATER
}

// A single data class to hold the state of all checkboxes.
data class ChartUiState(
    val intTempState: Boolean = true,
    val extTempState: Boolean = true,
    val intHumidityState: Boolean = true,
    val extHumidityState: Boolean = true,
    val ktpState: Boolean = true,
    val chamber1State: Boolean = true,
    val chamber2State: Boolean = true,
    val basePlateState: Boolean = true,
    val waterState: Boolean = true,
)

@HiltViewModel
class InfoViewModel @Inject constructor(
) : ViewModel() {

    // This is the single source of truth for the checkbox states.
    private val _chartUiState = MutableStateFlow(ChartUiState())
    val chartUiState = _chartUiState.asStateFlow()

    // A single, clean function to handle toggling any checkbox.
    fun toggleLine(line: ChartLine) {
        // .update is a thread-safe way to update the state.
        _chartUiState.update { currentState ->
            when (line) {
                ChartLine.INT_TEMP -> currentState.copy(intTempState = !currentState.intTempState)
                ChartLine.EXT_TEMP -> currentState.copy(extTempState = !currentState.extTempState)
                ChartLine.INT_HUMIDITY -> currentState.copy(intHumidityState = !currentState.intHumidityState)
                ChartLine.EXT_HUMIDITY -> currentState.copy(extHumidityState = !currentState.extHumidityState)
                ChartLine.KTP -> currentState.copy(ktpState = !currentState.ktpState)
                ChartLine.CHAMBER1 -> currentState.copy(chamber1State = !currentState.chamber1State)
                ChartLine.CHAMBER2 -> currentState.copy(chamber2State = !currentState.chamber2State)
                ChartLine.BASE_PLATE -> currentState.copy(basePlateState = !currentState.basePlateState)
                ChartLine.WATER -> currentState.copy(waterState = !currentState.waterState)
            }
        }
    }

    init {
        Timber.d("InfoViewModel init")
    }
}