package com.swago.baseswago.im

import com.tencent.imsdk.v2.V2TIMMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

/**
 *@date 2021/10/1 11:03
 *description:
 */
object IMMessageManager {

    val groupMessageParser = ArrayList<IGroupNewMsgParser>()

    val listener = ArrayList<IGroupNewMsg>()
    fun addGroupMsgListener(iGroupNewMsg: IGroupNewMsg){
        listener.add(iGroupNewMsg)
    }
    fun removeGroupMsgListener(iGroupNewMsg: IGroupNewMsg){
        listener.remove(iGroupNewMsg)
    }

    fun onNewMessage(v2TIMMessage: V2TIMMessage?){
        GlobalScope.launch(Dispatchers.Main) {
            v2TIMMessage?.let {

                if (it.groupID.isNotEmpty()){
                    //群组消息
                    val task = async {
                        var iGroupNewMsgBean:IGroupNewMsgBean? = null
                        groupMessageParser.forEach {
                            iGroupNewMsgBean = it.parserGroupMsg(v2TIMMessage)
                            if (iGroupNewMsgBean!=null){
                                return@forEach
                            }
                        }
                        iGroupNewMsgBean
                    }
                    val parserBean = task.await()?:return@launch
                    listener.forEach {
                        it.onNewMessage(parserBean)
                    }
                }
            }
        }
    }

}