package xyz.cottongin.radio247.service

import android.content.Intent
import xyz.cottongin.radio247.RadioApplication
import xyz.cottongin.radio247.data.model.Station
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class RadioController(
    private val application: RadioApplication
) {
    private val _state = MutableStateFlow<PlaybackState>(PlaybackState.Idle)
    val state: StateFlow<PlaybackState> = _state.asStateFlow()

    private val _estimatedLatencyMs = MutableStateFlow(0L)
    val estimatedLatencyMs: StateFlow<Long> = _estimatedLatencyMs.asStateFlow()

    fun play(station: Station) {
        val current = _state.value
        if (current is PlaybackState.Connecting && current.station.id == station.id) return
        _state.value = PlaybackState.Connecting(station)
        val intent = Intent(application, RadioPlaybackService::class.java).apply {
            action = RadioPlaybackService.ACTION_PLAY
            putExtra(RadioPlaybackService.EXTRA_STATION_ID, station.id)
        }
        application.startForegroundService(intent)
    }

    fun stop() {
        _state.value = PlaybackState.Idle
        val intent = Intent(application, RadioPlaybackService::class.java).apply {
            action = RadioPlaybackService.ACTION_STOP
        }
        application.startService(intent)
    }

    fun pause() {
        val current = _state.value
        if (current is PlaybackState.Playing) {
            _state.value = PlaybackState.Paused(
                station = current.station,
                metadata = current.metadata,
                sessionStartedAt = current.sessionStartedAt,
                streamInfo = current.streamInfo
            )
        }
        val intent = Intent(application, RadioPlaybackService::class.java).apply {
            action = RadioPlaybackService.ACTION_PAUSE
        }
        application.startService(intent)
    }

    fun seekToLive() {
        val intent = Intent(application, RadioPlaybackService::class.java).apply {
            action = RadioPlaybackService.ACTION_SEEK_LIVE
        }
        application.startService(intent)
    }

    internal fun updateState(state: PlaybackState) {
        _state.value = state
    }

    internal fun updateLatency(ms: Long) {
        _estimatedLatencyMs.value = ms
    }
}
