package com.swago.room.gift.control

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import com.opensource.svgaplayer.SVGACallback
import com.opensource.svgaplayer.SVGADrawable
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import com.swago.baseswago.model.live.gift.IMGiftModel
import com.swago.baseswago.util.LogUtil
import com.swago.room.databinding.ViewSvgaBinding
import java.net.URL

/**
 *@date 2021/12/11 17:04
 *description:
 */
class XSvgPlayer : ConstraintLayout {

    private var binding:ViewSvgaBinding? = null
    private var svgaParser:SVGAParser? = null

    var nextSvgPlay:(()->Unit)? = null

    /**
     * 是否正在播放svg
     */
    var isCanPlay = false

    constructor(context: Context) : super(context)
    constructor(context: Context, mAttributeSet: AttributeSet?) : super(context, mAttributeSet){
        initView(context)
    }

    private fun initView(context: Context) {
        binding = ViewSvgaBinding.inflate(LayoutInflater.from(context),this,true)
        svgaParser = SVGAParser(context)
    }


    fun playSvga(imGiftModel:IMGiftModel){
        svgaParser!!.let {
            isCanPlay = true
            it.parse(URL(imGiftModel.svga),object:SVGAParser.ParseCompletion{
                override fun onComplete(videoItem: SVGAVideoEntity) {
                    binding!!.apply {
                        val drawable = SVGADrawable(videoItem)
                        svgaImageView.visibility = View.VISIBLE
                        svgaImageView.setImageDrawable(drawable)
                        svgaImageView.loops = 1
                        svgaImageView.callback = callback
                        LogUtil.d("svgPlayer","dddd--$isCanPlay")
                        if (isCanPlay){
                            svgaImageView.startAnimation()
                        }

                    }

                }

                override fun onError() {
                    binding?.apply {
                        isCanPlay = false
                        svgaImageView.visibility = View.GONE
                        nextSvgPlay?.invoke()
                    }
                }

            })
        }
    }

    fun clear(){
        binding?.apply {
            isCanPlay = false
            svgaImageView.pauseAnimation()
            svgaImageView.clear()
        }

    }

    private var callback = object:SVGACallback {

        override fun onFinished() {
            LogUtil.d("svgPlayer","dddd--结束")
            isCanPlay = false
            binding?.svgaImageView?.visibility = View.GONE
            nextSvgPlay?.invoke()
        }

        override fun onPause() {
            
        }

        override fun onRepeat() {
            
        }

        override fun onStep(frame: Int, percentage: Double) {
            
        }
    }

}