package com.aves.google_cast.fast

import android.util.Log
import com.aves.google_cast.cast.CastContextManager
import com.aves.google_cast.cast.CastMediaClient
import com.google.android.gms.cast.MediaStatus
import com.google.android.gms.cast.framework.media.RemoteMediaClient
import io.flutter.plugin.common.MethodChannel

class FastCastEngine(
    private val contextManager: CastContextManager,
    private val mediaClient: CastMediaClient,
    private val channel: MethodChannel
) {

    private val tag = "FAST_CAST"

    fun loadQueue(args: Map<*, *>) {
        val items = args["items"] as List<Map<*, *>>
        val startIndex = args["startIndex"] as Int

        val castContext = contextManager.ensureCastContext()
        val session = castContext?.sessionManager?.currentCastSession
        val client = session?.remoteMediaClient

        if (client == null) {
            Log.w(tag, "No RemoteMediaClient available")
            return
        }

        val queueItems = FastQueueBuilder.buildItems(items)
        val repeatMode = FastQueueBuilder.repeatAll()

        client.queueLoad(
            queueItems.toTypedArray(),
            startIndex,
            repeatMode,
            null
        )

        client.addListener(object : RemoteMediaClient.Listener {
            override fun onStatusUpdated() {
                val status = client.mediaStatus ?: return

                sendEvent("currentIndex", status.currentItemId)

                val playerState = status.playerState
                sendEvent("isPlaying", playerState == MediaStatus.PLAYER_STATE_PLAYING)
                sendEvent("isBuffering", playerState == MediaStatus.PLAYER_STATE_BUFFERING)
            }

            override fun onMetadataUpdated() {}
            override fun onQueueStatusUpdated() {}
            override fun onPreloadStatusUpdated() {}
            override fun onSendingRemoteMediaRequest() {}
            override fun onAdBreakStatusUpdated() {}
        })

        Log.d(tag, "FAST queue loaded: ${queueItems.size} items, start=$startIndex")
    }

    fun next() {
        currentClient()?.queueNext(null)
    }

    fun prev() {
        currentClient()?.queuePrev(null)
    }

    fun stop() {
        currentClient()?.stop()
    }

    private fun currentClient(): RemoteMediaClient? {
        val castContext = contextManager.ensureCastContext()
        val session = castContext?.sessionManager?.currentCastSession
        return session?.remoteMediaClient
    }

    private fun sendEvent(event: String, value: Any) {
        channel.invokeMethod("fastEvent", mapOf("event" to event, "value" to value))
    }
}
