package com.swago.room.gift.control

import android.content.Context
import com.opensource.svgaplayer.SVGAParser
import com.swago.baseswago.baseroom.IRoomActiveListener
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.model.live.gift.IMGiftModel
import com.swago.baseswago.util.LogUtil
import java.util.*

/**
 *@date 2021/12/11 16:42
 *description:
 */
class SvgPlayerManager : IRoomActiveListener {

    private val svgListQueue = LinkedList<IMGiftModel>()
    private var xSvgPlayer: XSvgPlayer? = null

    fun init(context: Context, xSvgPlayer: XSvgPlayer) {
        SVGAParser.shareParser().init(context)
        this.xSvgPlayer = xSvgPlayer
        SwagoRoomManager.addListener(this)

        this.xSvgPlayer?.nextSvgPlay = {
            svgListQueue.poll()
            val imGiftModel = svgListQueue.peek()
            LogUtil.d("SvgPlayerManager","${svgListQueue.size}")
            if (imGiftModel==null){
                LogUtil.d("SvgPlayerManager","clear svgListQueue")
                svgListQueue.clear()
            }else{
                if (this.xSvgPlayer==null){
                    svgListQueue.clear()
                    LogUtil.d("SvgPlayerManager","xSvgPlayer 为空")
                }else{
                    this.xSvgPlayer!!.playSvga(imGiftModel)
                }

            }
        }
    }

    override fun changeRoom(iRoomInfo: IRoomInfo) {
        svgListQueue.clear()
        xSvgPlayer?.clear()
    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
        svgListQueue.clear()
        xSvgPlayer?.clear()
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {

    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {

    }

    override fun closeRoomed() {
        svgListQueue.clear()
        xSvgPlayer?.clear()
        SwagoRoomManager.removeListener(this)
    }


    fun addSvgUrl(imGiftModel: IMGiftModel?) {
        LogUtil.d("SvgPlayerManager","数据")
        imGiftModel?.let {
            if (svgListQueue.isEmpty()) {
                svgListQueue.add(it)
                this.xSvgPlayer?.playSvga(it)
            } else {
                this.xSvgPlayer?.apply {
                    if (this.isCanPlay){
                        svgListQueue.add(it)
                    }else{
                        svgListQueue.clear()
                        svgListQueue.add(it)
                        this.playSvga(it)
                    }
                }
            }
        }
    }
}