package com.swago.baseswago.baseroom

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message

/**
 *@date 2021/10/3 10:41
 *description:
 */
object RoomTimer : IRoomActiveListener{

    private var isInRoom = false
    var currentTime = 0
    const val TIME_TICK = 100

    interface TimeTickListener {
        fun onTimeCount(time:Int)
    }

    val timeTickList = ArrayList<TimeTickListener>()

    fun init(){
        SwagoRoomManager.addListener(this)
    }

    private var handler = @SuppressLint("HandlerLeak")
    object: Handler(){
        override fun handleMessage(msg: Message) {
            if (!isInRoom){
                return
            }
            when(msg.what){
                TIME_TICK -> {
                    timeTickList.forEach { listener ->
                        listener.onTimeCount(currentTime)
                    }
                    currentTime++
                    sendEmptyMessageDelayed(TIME_TICK,1000)
                }
            }
        }
    }

    override fun changeRoom(iRoomInfo: IRoomInfo) {}

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
        isInRoom = false
        currentTime = 0
        handler.removeCallbacksAndMessages(null)
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {
        currentTime = 0
        isInRoom = true
        handler.removeCallbacksAndMessages(null)
        handler.sendEmptyMessage(TIME_TICK)
    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {}


    override fun closeRoomed() {
        currentTime = 0
        isInRoom = false
        handler.removeCallbacksAndMessages(null)
        SwagoRoomManager.removeListener(this)
    }

    fun clear(){
        handler.removeCallbacksAndMessages(null)
    }

}