package com.swago.room.hongbao

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import com.swago.baseswago.baseroom.IRoomActiveListener
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.RoomTimer
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.model.RedEnvelope
import com.swago.baseswago.util.NoDoubleClickListener
import com.swago.loadUrl
import com.swago.room.databinding.ViewRedBroadCastBinding

class RedEnvelopeBroadcastView : FrameLayout, IRoomActiveListener,RoomTimer.TimeTickListener {

    private var binding:ViewRedBroadCastBinding? = null

    var openRedEnvelopeBroadcastDialog:((redEnvelope:RedEnvelope)->Unit)? = null

    private var envelope:RedEnvelope? = null

    private var count = 0

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        initView()
    }

    private fun initView() {
        RoomTimer.timeTickList.add(this)
        SwagoRoomManager.addListener(this)
        binding = ViewRedBroadCastBinding.inflate(LayoutInflater.from(context), this, true)
        binding?.root?.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                envelope?.let {
                    openRedEnvelopeBroadcastDialog?.invoke(it)
                }
            }
        })
    }

    fun setRedEnvelopeBroadcastData(redEnvelope:RedEnvelope){
        count = 10
        envelope = redEnvelope
        binding?.ivAvatar?.loadUrl(context,redEnvelope.anchorAvatar)
        visibility = View.VISIBLE
    }

    override fun changeRoom(iRoomInfo: IRoomInfo) {
    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
        envelope = null
        visibility = View.GONE
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {
    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {
    }

    override fun closeRoomed() {
        envelope = null
        RoomTimer.timeTickList.remove(this)
        SwagoRoomManager.removeListener(this)
        visibility = View.GONE
    }

    override fun onTimeCount(time: Int) {
        count--
        if (count==0){
            visibility = View.GONE
        }
    }
}