package com.example.polaritychecker

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

enum class PolarityResult { WAITING, POSITIVE, NEGATIVE }

class MainViewModel : ViewModel() {
    private val _selectedFrequency = MutableStateFlow("1k2Hz")
    val selectedFrequency: StateFlow<String> = _selectedFrequency.asStateFlow()

    private val _isPlaying = MutableStateFlow(false)
    val isPlaying: StateFlow<Boolean> = _isPlaying.asStateFlow()

    private val _isInverted = MutableStateFlow(false)
    val isInverted: StateFlow<Boolean> = _isInverted.asStateFlow()

    private val _threshold = MutableStateFlow(-17.0f)
    val threshold: StateFlow<Float> = _threshold.asStateFlow()

    private val _inputLevel = MutableStateFlow(-60.0f)
    val inputLevel: StateFlow<Float> = _inputLevel.asStateFlow()

    private val _polarityResult = MutableStateFlow(PolarityResult.WAITING)
    val polarityResult: StateFlow<PolarityResult> = _polarityResult.asStateFlow()

    private val audioGenerator = AudioGenerator()
    private val audioAnalyzer = AudioAnalyzer(
        onLevelUpdate = { level ->
            _inputLevel.value = level
        },
        onPolarityDetected = { isPositive ->
            _polarityResult.value = if (isPositive) PolarityResult.POSITIVE else PolarityResult.NEGATIVE
            
            // We no longer auto-reset to WAITING. 
            // The result will hold on screen until a new pulse is detected,
            // or until the user changes settings, providing a much smoother experience.
        }
    )

    fun setFrequency(freq: String) {
        _selectedFrequency.value = freq
        if (_isPlaying.value) {
            audioGenerator.start(freq, _isInverted.value)
        }
    }

    fun togglePlay() {
        val newPlayState = !_isPlaying.value
        _isPlaying.value = newPlayState
        if (newPlayState) {
            audioGenerator.start(_selectedFrequency.value, _isInverted.value)
        } else {
            audioGenerator.stop()
        }
    }

    fun toggleInvert() {
        _isInverted.value = !_isInverted.value
        if (_isPlaying.value) {
            audioGenerator.start(_selectedFrequency.value, _isInverted.value)
        }
    }

    fun setThreshold(value: Float) {
        _threshold.value = value
        audioAnalyzer.thresholdDb = value
    }

    fun startAnalyzer() {
        audioAnalyzer.start()
    }

    fun stopAnalyzer() {
        audioAnalyzer.stop()
    }

    override fun onCleared() {
        super.onCleared()
        audioGenerator.stop()
        audioAnalyzer.stop()
    }
}
