@file:OptIn(FlowPreview::class)

package dev.adriankuta.visualizer.view

import androidx.compose.ui.graphics.Color
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.adriankuta.visualizer.data.AudioVisualizerController
import dev.adriankuta.visualizer.domain.ObserveVisualizerColorUseCase
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.sample
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
import kotlin.time.Duration.Companion.milliseconds

@HiltViewModel
class VisualizerScreenViewModel @Inject constructor(
    observeVisualizerColorUseCase: ObserveVisualizerColorUseCase,
    private val audioVisualizerController: AudioVisualizerController
) : ViewModel() {

    private val _isActive = MutableStateFlow(false)

    val uiState = combine(
        observeVisualizerColorUseCase().sample(50.milliseconds),
        _isActive
    ) { color, isActive ->
        VisualizerScreenUiState(
            color = color,
            isActive = isActive
        )
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5_000),
        initialValue = VisualizerScreenUiState(
            color = Color.Black,
            isActive = false
        )
    )

    fun start() {
        audioVisualizerController.start()
        _isActive.value = true
    }

    fun stop() {
        audioVisualizerController.stop()
        _isActive.value = false
    }
}
