package com.aves.google_cast.cast

import com.google.android.gms.cast.MediaInfo
import com.google.android.gms.cast.MediaMetadata
import io.flutter.plugin.common.MethodChannel

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

    // ------------------------------------------------------------
    // AVVIO CUSTOM RECEIVER (CAF Web Receiver)
    // ------------------------------------------------------------
    fun startCustomReceiver(appId: String, receiverUrl: String) {
        val session = ctx.getSession() ?: return

        try {
            val metadata = MediaMetadata(MediaMetadata.MEDIA_TYPE_GENERIC)
            val mediaInfo = MediaInfo.Builder(receiverUrl)
                .setContentType("text/html")
                .setStreamType(MediaInfo.STREAM_TYPE_NONE)
                .setMetadata(metadata)
                .build()

            session.remoteMediaClient?.load(mediaInfo, true)
        } catch (e: Exception) {
            channel.invokeMethod(
                "onCastError",
                mapOf("message" to "Failed to start custom receiver: ${e.message}")
            )
        }
    }

    // ------------------------------------------------------------
    // INVIO MESSAGGI CUSTOM (compatibile con nuova Cast SDK)
    // ------------------------------------------------------------
    fun sendCustomMessage(message: String) {
        val session = ctx.getSession() ?: return

        try {
            val client = session.remoteMediaClient ?: return

            // TRUCCO: inviamo JSON come data URL
            val dataUrl = "data:application/json,$message"

            val mediaInfo = MediaInfo.Builder(dataUrl)
                .setContentType("application/json")
                .setStreamType(MediaInfo.STREAM_TYPE_NONE)
                .build()

            // load() = invio messaggio al Web Receiver
            client.load(mediaInfo, false)

        } catch (e: Exception) {
            channel.invokeMethod(
                "onCastError",
                mapOf("message" to "sendCustomMessage exception: ${e.message}")
            )
        }
    }
}
