package com.swago.room.manager

import android.animation.Animator
import android.view.ViewStub
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.LottieCompositionFactory
import com.swago.baseswago.baseroom.IRoomActiveListener
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.constant.UrlConstant
import com.swago.baseswago.model.im.UserJoinRoomBean
import com.swago.baseswago.util.DpPxUtil
import com.swago.baseswago.util.FileUtil
import com.swago.baseswago.util.SwagoInfo
import com.swago.loadUrl
import com.swago.room.R
import de.hdodenhof.circleimageview.CircleImageView
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.util.LinkedList
import java.util.zip.ZipInputStream

class JoinRoomManager : IRoomActiveListener {

    private var mActivity: FragmentActivity? = null
    private var isRunning = false
    private var lottieView: LottieAnimationView? = null
    private var tvName: TextView? = null
    private var ivAvatar: CircleImageView? = null
    private var joinRoomRootView: ConstraintLayout? = null
    private var clBg: ConstraintLayout? = null
    private var animationSet: AnimatorSet? = null
    private var lottieMoto: LottieComposition? = null
    private var lottieCar: LottieComposition? = null
    private var lottieBoat: LottieComposition? = null
    private var lottieRider: LottieComposition? = null
    private val waitingTime = 1000L

    private var joinRoomList = LinkedList<UserJoinRoomBean>()
    private var canAddData = true

    fun initViewStub(viewStub: ViewStub?, activity: FragmentActivity?) {
        mActivity = activity
        viewStub?.apply {
            val view = this.inflate()
            lottieView = view.findViewById(R.id.lottieView)
            clBg = view.findViewById(R.id.clBg)
            tvName = view.findViewById(R.id.tvName)
            ivAvatar = view.findViewById(R.id.ivAvatar)
            joinRoomRootView = view.findViewById(R.id.rootView)
            initLottieComposition()
            initViewAnimation()
            loopStart()
            SwagoRoomManager.addListener(this@JoinRoomManager)
        }

    }

    private fun loopStart() {
        Thread {
            while (true) {
                if (!canAddData) break
                if (joinRoomList.isEmpty() || isRunning) {
                    Thread.sleep(waitingTime)
                    continue
                }
                joinRoomList.peek() ?: continue
                val userJoinRoomBean = joinRoomList.poll() ?: continue
                mActivity?.let {
                    it.runOnUiThread {
                        playJoinRoomAnimation(userJoinRoomBean)
                    }
                }
            }
        }.start()
    }

    private fun playJoinRoomAnimation(userJoinRoomBean: UserJoinRoomBean) {
        isRunning = true
        joinRoomRootView?.visibility = View.VISIBLE
        mActivity?.let { ivAvatar?.loadUrl(it, userJoinRoomBean.userAvatar) }
        tvName?.text = userJoinRoomBean.senderName
        if (userJoinRoomBean.isBenefit == 1) {
            if (lottieRider == null) {
                isRunning = false
            } else {
                lottieRider?.let {
                    clBg?.setBackgroundResource(R.drawable.shape_e87230_ddb558_all_20)
                    lottieView?.setComposition(it)
                    lottieView?.playAnimation()
                    animationSet?.start()
                }
            }
        } else {
            if (userJoinRoomBean.senderLevel in 20..39) {
                if (lottieMoto == null) {
                    isRunning = false
                } else {
                    lottieMoto?.let {
                        clBg?.setBackgroundResource(R.drawable.shape_6720d1_180c72_20)
                        lottieView?.setComposition(it)
                        lottieView?.playAnimation()
                        animationSet?.start()
                    }
                }
            }
            if (userJoinRoomBean.senderLevel in 40..59) {
                if (lottieCar == null) {
                    isRunning = false
                } else {
                    lottieCar?.let {
                        clBg?.setBackgroundResource(R.drawable.shape_f8614b_8c2922_20)
                        lottieView?.setComposition(it)
                        lottieView?.playAnimation()
                        animationSet?.start()
                    }
                }
            }

            if (userJoinRoomBean.senderLevel >= 60) {
                if (lottieBoat == null) {
                    isRunning = false
                } else {
                    lottieBoat?.let {
                        clBg?.setBackgroundResource(R.drawable.shape_434343_000000_20)
                        lottieView?.setComposition(it)
                        lottieView?.playAnimation()
                        animationSet?.start()
                    }
                }
            }
        }
    }

    private fun initViewAnimation() {
        joinRoomRootView?.let {
            animationSet = AnimatorSet()
            val screenWidth = DpPxUtil.getScreenWidth().toFloat()
            val joinRoomObjectAnimator = ObjectAnimator.ofFloat(
                it,
                "translationX",
                if (SwagoInfo.isMirror()) -screenWidth else screenWidth,
                0f
            )
            joinRoomObjectAnimator.interpolator = AccelerateInterpolator()
            joinRoomObjectAnimator.duration = 100

            val exitRoomObjectAnimator = ObjectAnimator.ofFloat(
                it,
                "translationX",
                0f,
                if (SwagoInfo.isMirror()) screenWidth else -screenWidth
            )
            joinRoomObjectAnimator.interpolator = DecelerateInterpolator()
            joinRoomObjectAnimator.duration = 100

            animationSet?.let { animationSet ->
                animationSet.play(exitRoomObjectAnimator)
                    .after(joinRoomObjectAnimator)
                    .after(4000)
                animationSet.addListener(object : Animator.AnimatorListener {
                    override fun onAnimationStart(p0: Animator) {
                        joinRoomRootView?.visibility = View.VISIBLE
                    }

                    override fun onAnimationEnd(p0: Animator) {
                        joinRoomRootView?.visibility = View.INVISIBLE
                        isRunning = false
                    }

                    override fun onAnimationCancel(p0: Animator) {
                    }

                    override fun onAnimationRepeat(p0: Animator) {
                    }
                })
            }
        }
    }

    private fun initLottieComposition() {
        try {
            LottieCompositionFactory.fromZipStream(
                ZipInputStream(FileInputStream(UrlConstant.lottieResourcePath + File.separator + "lottiemoto.zip")),
                "lottiemoto"
            ).addListener {
                lottieMoto = it
            }

            LottieCompositionFactory.fromZipStream(
                ZipInputStream(FileInputStream(UrlConstant.lottieResourcePath + File.separator + "lottiecar.zip")),
                "lottiecar"
            ).addListener {
                lottieCar = it
            }

            LottieCompositionFactory.fromZipStream(
                ZipInputStream(FileInputStream(UrlConstant.lottieResourcePath + File.separator + "lottieboat.zip")),
                "lottieboat"
            ).addListener {
                lottieBoat = it
            }

            LottieCompositionFactory.fromZipStream(
                ZipInputStream(FileInputStream(UrlConstant.lottieResourcePath + File.separator + "lottierider.zip")),
                "lottierider"
            ).addListener {
                lottieRider = it
            }
        } catch (e: FileNotFoundException) {
            FileUtil.deleteFile(File(UrlConstant.lottieResourcePath))
            e.printStackTrace()
        }
    }


    fun addJoinRoomData(joinRoomBean: UserJoinRoomBean) {
        joinRoomList.add(joinRoomBean)
    }


    override fun changeRoom(iRoomInfo: IRoomInfo) {
        isRunning = false
        clearJoinRoomAnimation()
    }

    private fun clearJoinRoomAnimation() {
        animationSet?.cancel()
        joinRoomList.clear()
        joinRoomRootView?.visibility = View.INVISIBLE
    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {
    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {
        clearJoinRoomAnimation()
    }

    override fun closeRoomed() {
        canAddData = false
        clearJoinRoomAnimation()
        SwagoRoomManager.removeListener(this)
    }
}