package com.hermes.app.core.media

import android.content.Context
import android.net.Uri
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class HermesPlayerCoordinator(context: Context) {
    val player: ExoPlayer = ExoPlayer.Builder(context.applicationContext).build()

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

    fun preparePreview(mediaUrl: String) {
        player.setMediaItem(MediaItem.fromUri(Uri.parse(mediaUrl)))
        player.prepare()
        player.playWhenReady = true
        _isPlaying.value = true
    }

    fun play() {
        player.play()
        _isPlaying.value = true
    }

    fun pause() {
        player.pause()
        _isPlaying.value = false
    }

    fun restart(mediaUrl: String) {
        preparePreview(mediaUrl)
        player.seekTo(0)
    }

    fun release() {
        player.release()
    }
}
