package com.adealink.weparty.room.theme

import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.OptIn
import androidx.lifecycle.LifecycleOwner
import androidx.media3.common.util.UnstableApi
import com.adealink.frame.apm.monitor.PerformanceHelper
import com.adealink.frame.effect.video.WeVideoView
import com.adealink.frame.effect.video.controller.IWeVideoPlayListener
import com.adealink.frame.effect.video.controller.VideoScalingMode
import com.adealink.frame.effect.video.controller.VideoViewResizeMode
import com.adealink.frame.image.view.NetworkImageView
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.safeAction
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.module.room.base.BaseRoomComp
import com.adealink.weparty.room.R
import com.adealink.weparty.room.theme.data.DynamicThemeResourceType
import com.adealink.weparty.room.theme.data.ThemeResource
import com.facebook.drawee.drawable.ScalingUtils
import com.opensource.svgaplayer.WenextSvgaView
import com.opensource.svgaplayer.control.ControllerListener
import com.opensource.svgaplayer.entities.SvgaInfo

class ThemeComp(
    lifecycleOwner: LifecycleOwner,
    private val bgContainer: FrameLayout,
    private val defaultRoomBg: Int,
) : BaseRoomComp(lifecycleOwner) {

    override fun initViews() {
        super.initViews()
        showDefaultRoomBg(true)
    }

    private fun inflateRoomImgBg(removeAllView: Boolean): NetworkImageView {
        var imgView = bgContainer.findViewById<NetworkImageView>(R.id.id_room_bg_type_img)
        if (imgView != null) {
            return imgView
        }
        imgView = NetworkImageView(bgContainer.context).apply {
            hierarchy?.setPlaceholderImage(defaultRoomBg)
            hierarchy?.actualImageScaleType = ScalingUtils.ScaleType.CENTER_CROP
        }
        if (removeAllView) {
            bgContainer.removeAllViews()
        }
        bgContainer.addView(
            imgView, FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
        )
        return imgView
    }

    private fun inflateRoomSvgaBg(removeAllView: Boolean): WenextSvgaView {
        var svgaView = bgContainer.findViewById<WenextSvgaView>(R.id.id_room_bg_type_img)
        if (svgaView != null) {
            return svgaView
        }
        svgaView = WenextSvgaView(bgContainer.context).apply {
            scaleType = ImageView.ScaleType.CENTER_CROP
        }
        if (removeAllView) {
            bgContainer.removeAllViews()
        }
        bgContainer.addView(
            svgaView, FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
        )
        return svgaView
    }


    @OptIn(UnstableApi::class)
    private fun inflateRoomMp4Bg(removeAllView: Boolean): WeVideoView {
        var mp4View = bgContainer.findViewById<WeVideoView>(R.id.id_room_bg_type_mp4)
        if (mp4View != null) {
            return mp4View
        }
        mp4View = WeVideoView(bgContainer.context)
        if (removeAllView) {
            bgContainer.removeAllViews()
        }
        bgContainer.addView(
            mp4View, FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
        )
        mp4View.setResizeMode(VideoViewResizeMode.Fill)
        mp4View.setShowControllerBar(false)
        mp4View.background = null
        return mp4View
    }

    private fun showDefaultRoomBg(removeAllView: Boolean) {
        val imgView = inflateRoomImgBg(removeAllView)
        imgView.show()
        imgView.hierarchy?.actualImageScaleType = ScalingUtils.ScaleType.CENTER_CROP
        imgView.setActualImageResource(defaultRoomBg)
        imgView.background = null
    }

    private fun showStaticTheme(staticUrl: String?, removeAllView: Boolean) {
        val imgView = inflateRoomImgBg(removeAllView)
        imgView.show()
        imgView.hierarchy?.actualImageScaleType = ScalingUtils.ScaleType.CENTER_CROP
        imgView.setImageUrl(staticUrl)
        imgView.background = null
    }

    @OptIn(UnstableApi::class)
    private fun showDynamicTheme(themeResource: ThemeResource) {
        if (!themeResource.isDynamicResource()) {
            showDefaultRoomBg(true)
            return
        }
        //低端机内存占用高时，不播放视频主题，使用静态主题
        if (themeResource.getDynamicResourceType() == DynamicThemeResourceType.MP4 && PerformanceHelper.isWeakDeviceMemoryUsageHigh()) {
            showStaticTheme(themeResource.staticResourceUrl, true)
            return
        }

        when (themeResource.getDynamicResourceType()) {
            DynamicThemeResourceType.SVGA -> {
                val imgView = inflateRoomImgBg(false)
                showDefaultRoomBg(false)

                val svgaView = inflateRoomSvgaBg(false)
                svgaView.show()
                svgaView.setUrl(
                    themeResource.dynamicResourceUrl,
                    listener = object : ControllerListener {
                        override fun onBeforeImageSet(id: String?, svgaInfo: SvgaInfo?) {
                            super.onBeforeImageSet(id, svgaInfo)
                            if (!isValid) {
                                return
                            }
                            imgView.gone()
                        }

                        override fun onFailure(id: String?, throwable: Throwable?) {
                            bgContainer.safeAction {
                                if (isValid) {
                                    showDefaultRoomBg(true)
                                }
                            }
                        }
                    })
            }

            DynamicThemeResourceType.MP4 -> {
                val mp4ThemeFilePath = themeResource.savePath?.use()
                if (mp4ThemeFilePath.isNullOrEmpty()) {
                    showDefaultRoomBg(true)
                    return
                }
                val imgView = inflateRoomImgBg(false)
                showDefaultRoomBg(false)

                val mp4View = inflateRoomMp4Bg(false)
                mp4View.show()
                //等视频准备好再显示，先设置透明度0, 视频未准备好会出现黑屏
                mp4View.clearAnimation()
                mp4View.alpha = 0f
                mp4View.setVideoScalingMode(VideoScalingMode.ScaleToFitWithCropping)
                mp4View.setLoopCount(-1)
                mp4View.setAutoPlay(true)
                mp4View.setVolume(0f)
                mp4View.setUri(mp4ThemeFilePath)
                mp4View.setListener(object : IWeVideoPlayListener {
                    override fun onPlayReady() {
                        super.onPlayReady()
                        if (isValid) {
                            imgView.gone()
                            mp4View.startAnimation(
                                AlphaAnimation(0f, 1f).apply {
                                    duration = 300
                                    setAnimationListener(object : AnimationListener {
                                        override fun onAnimationStart(animation: Animation?) {

                                        }

                                        override fun onAnimationEnd(animation: Animation?) {
                                            bgContainer.safeAction {
                                                if (isValid) {
                                                    mp4View.alpha = 1f
                                                }
                                            }
                                        }

                                        override fun onAnimationRepeat(animation: Animation?) {

                                        }
                                    })
                                }
                            )
                        }
                    }

                    override fun onPlayerError(error: String) {
                        super.onPlayerError(error)
                        bgContainer.safeAction {
                            if (isValid) {
                                showDefaultRoomBg(true)
                            }
                        }
                    }
                })
            }

            else -> {
                showDefaultRoomBg(true)
            }
        }
    }
}