package cn.org.bjca.trust.push.manager

import android.content.Context
import cn.org.bjca.trust.push.BuildConfig
import cn.org.bjca.trust.push.common.CommonHelper
import cn.org.bjca.trust.push.common.DeviceHelper
import cn.org.bjca.trust.push.common.LogHelper
import cn.org.bjca.trust.push.enums.OsType
import cn.org.bjca.trust.push.kit.SdkInterface
import cn.org.bjca.trust.push.message.ImCallback
import cn.org.bjca.trust.push.message.ImManager
import cn.org.bjca.trust.push.message.bean.TextMessage
import cn.org.bjca.trust.push.message.callback.CallbackListener
import cn.org.bjca.trust.push.message.client.ImConnectOptions
import cn.org.bjca.trust.push.message.msg.Message
import cn.org.bjca.trust.push.message.msg.SendMessage

class PushSdkManager : SdkInterface {

    lateinit var imConnectOptions: ImConnectOptions

    override fun register(context: Context, userId: String) {
        //先关闭已有连接
        if (ImManager.instance.isConnect() || ImManager.instance.isConnecting()) {
            ImManager.instance.disConnect()
        }

        if (::imConnectOptions.isInitialized) {
            imConnectOptions.clientId = userId
            imConnectOptions.host = "192.168.115.173"
            imConnectOptions.port = 1883
            imConnectOptions.deviceId = DeviceHelper.getDeviceId()
            imConnectOptions.token = "token"
            imConnectOptions.osType = OsType.ANDROID
            imConnectOptions.sdkVersion = BuildConfig.versionName
        } else {
            imConnectOptions = ImConnectOptions(
                "192.168.115.173",
                1883,
                userId,
                DeviceHelper.getDeviceId(),
                "token",
                OsType.ANDROID,
                BuildConfig.versionName
            )
        }
        imConnectOptions.callback = ImCallback()
        ImManager.instance.connect(context, imConnectOptions)
    }

    override fun unregister(context: Context, userId: String) {
        TODO("Not yet implemented")
    }


    override fun setMsgCallback(callback: CallbackListener) {
        imConnectOptions.callback = callback
    }

    override fun sendTextMessage(toUserId: String, msg: String) {

        sendMessage(TextMessage().apply {
            toClientId = toUserId
            text = msg
        })
    }

    override fun sendMessage(message: Message) {
        LogHelper.d("------app端调用发送消息-----")
        val sendMessage = SendMessage()
        sendMessage.messageId = message.messageId ?: CommonHelper.generateMessageId()
        sendMessage.timestamp = System.currentTimeMillis()
        sendMessage.fromClientId = imConnectOptions.clientId
        sendMessage.toClientId = message.toClientId
        sendMessage.target = imConnectOptions.clientId
        sendMessage.messageType = message.msgType.value
        sendMessage.message = message.createContentJsonStr()


        ImManager.instance.sendMessage(sendMessage)
    }
}