package com.nothing.camera2magic.viewmodel

import android.util.Log
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import androidx.lifecycle.ViewModel
import com.nothing.camera2magic.hook.HalConfigManager

private const val TAG = "SettingsViewModel"

class SettingsViewModel(private val repository: ConfigRepository) : ViewModel() {

    private val _uiState = MutableStateFlow(SettingsUiState())
    val uiState = _uiState.asStateFlow()

    init {
        loadInitialSettings()
    }

    private fun loadInitialSettings() {
        _uiState.value = SettingsUiState(
            playSound = repository.playSound,
            enableLog = repository.enableLog,
            injectMenu = repository.injectMenu,
            manuallyRotate = repository.manuallyRotate,
            halModeEnabled = repository.halModeEnabled
        )
    }
    fun onPlaySoundToggled() {
        _uiState.update { currentState ->
            val newState = !currentState.playSound
            repository.playSound = newState
            currentState.copy(playSound = newState)
        }
    }

    fun onEnableLogToggled() {
        _uiState.update { currentState ->
            val newState = !currentState.enableLog
            repository.enableLog = newState
            currentState.copy(enableLog = newState)
        }
    }

    fun onInjectMenuToggled() {
        _uiState.update { currentState ->
            val newState = !currentState.injectMenu
            repository.injectMenu = newState
            currentState.copy(injectMenu = newState)
        }
    }
    fun onManuallyRotateToggled() {
        _uiState.update { currentState ->
            val newState = !currentState.manuallyRotate
            repository.manuallyRotate = newState
            currentState.copy(manuallyRotate = newState)
        }
    }

    fun onHalModeToggled() {
        _uiState.update { currentState ->
            val newState = !currentState.halModeEnabled
            repository.halModeEnabled = newState

            val success = HalConfigManager.writeConfig(
                enabled = newState,
                sourceMode = repository.halSourceMode,
                videoPath = repository.halVideoPath,
                rtspUrl = repository.halRtspUrl
            )
            if (success) {
                Log.i(TAG, "HAL mode ${if (newState) "enabled" else "disabled"}, config written")
            } else {
                Log.w(TAG, "HAL mode toggled but config write failed (root required)")
            }

            currentState.copy(halModeEnabled = newState)
        }
    }
}

data class SettingsUiState(
    val playSound: Boolean = false,
    val enableLog: Boolean = false,
    val injectMenu: Boolean = false,
    val manuallyRotate: Boolean = false,
    val halModeEnabled: Boolean = false
)
