package com.aves.google_cast.cast

import com.google.android.gms.cast.*
import io.flutter.plugin.common.MethodChannel
import org.json.JSONObject

class CastQueueManager(
    private val ctx: CastContextManager,
    private val channel: MethodChannel
) {

    fun loadQueue(items: List<Map<String, Any>>, startIndex: Int) {
        val client = ctx.getClient() ?: return

        val queueItems = items.mapIndexed { index, it ->
            val url = it["url"] as String
            val isVideo = it["isVideo"] as Boolean
            val mime = it["mimeType"] as String

            val metadata = MediaMetadata(
                if (isVideo) MediaMetadata.MEDIA_TYPE_MOVIE
                else MediaMetadata.MEDIA_TYPE_PHOTO
            )

            val custom = JSONObject()
                .put("index", index)
                .put("isVideo", isVideo)

            val mediaInfo = MediaInfo.Builder(url)
                .setContentType(mime)
                .setStreamType(
                    if (isVideo) MediaInfo.STREAM_TYPE_BUFFERED
                    else MediaInfo.STREAM_TYPE_NONE
                )
                .setMetadata(metadata)
                .setCustomData(custom)
                .build()

            MediaQueueItem.Builder(mediaInfo)
                .setAutoplay(true)
                .setPreloadTime(8.0)
                .build()
        }

        client.queueLoad(
            queueItems.toTypedArray(),
            startIndex,
            MediaStatus.REPEAT_MODE_REPEAT_OFF,
            null
        )
    }

    fun next() {
        ctx.getClient()?.queueNext(null)
    }

    fun prev() {
        ctx.getClient()?.queuePrev(null)
    }
}
