package com.aves.google_cast.cast

import android.app.Activity
import android.view.ViewGroup
import androidx.mediarouter.app.MediaRouteButton
import com.google.android.gms.cast.framework.CastButtonFactory
import io.flutter.plugin.common.MethodChannel

class CastDialogLauncher(
    private val channel: MethodChannel
) {

    fun showCastDialog(activity: Activity) {
        activity.runOnUiThread {
            try {
                val button = MediaRouteButton(activity)
                CastButtonFactory.setUpMediaRouteButton(activity, button)

                val root = activity.findViewById<ViewGroup>(android.R.id.content)
                root?.addView(button, ViewGroup.LayoutParams(1, 1))

                button.performClick()
            } catch (e: Exception) {
                channel.invokeMethod(
                    "onCastError",
                    mapOf("message" to (e.message ?: "unknown"))
                )
            }
        }
    }
}
