package tech.nut.nut_player_android

import android.content.Context
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory
import tech.nut.player.NutPlayerView
import tech.nut.player.model.NutPlayer
import android.view.View
import android.widget.TextView
import android.graphics.Color
import tech.nut.player.plugins.pub.BrightnessVisualPlugin
import tech.nut.player.plugins.pub.ControlPanelVisualPlugin
import tech.nut.player.plugins.pub.VolumeVisualPlugin
import tech.nut.player.plugins.pub.ErrorPanelVisualPlugin

interface NutPlayerViewFactoryDelegate {
    fun player(playerId: Int): NutPlayer?
}

internal class NutPlayerViewFactory(private val delegate: NutPlayerViewFactoryDelegate):
    PlatformViewFactory(StandardMessageCodec.INSTANCE) {
    override fun create(context: Context, viewId: Int, args: Any?): PlatformView {

        val arguments = args as? Map<*, *>
        val playerId = arguments?.get("playerId") as? Int

        if (playerId == null) { return NativeView(context, viewId) }

        val player = delegate.player(playerId)
        if (player == null) { return NativeView(context, viewId) }

        val nutPlayerView = NutPlayerView(context)
        nutPlayerView.configure(
            nutPlayer = player,
            visualPlugins =
            listOf(
                // ControlPanelVisualPlugin(),
                // BrightnessVisualPlugin(),
                // VolumeVisualPlugin(),
                ErrorPanelVisualPlugin()
            )
        )

        return PlayerFlutterPlatformView(playerId, nutPlayerView)
    }
}

internal class NativeView(context: Context, id: Int) : PlatformView {
    private val textView: TextView
    override fun getView(): View { return textView }
    override fun dispose() {}
    init {
        textView = TextView(context)
        textView.textSize = 72f
        textView.setBackgroundColor(Color.rgb(255, 255, 255))
        textView.text = "Rendered on a native Android view (id: $id)"
    }
}