package com.waytous.anticollision.tcp

import com.blankj.utilcode.util.LogUtils
import com.waytous.anticollision.BuildConfig
import io.github.toggery.jt808.codec.Message
import io.github.toggery.jt808.codec.MessageMetadata
import io.github.toggery.jt808.messagebody.AbstractToStringJoiner
import io.github.toggery.jt808.messagebody.B8001
import io.github.toggery.jt808.messagebody.B8100
import io.github.toggery.jt808.messagebody.B8103
import io.netty.buffer.ByteBuf
import io.netty.util.DefaultAttributeMap
import io.netty.util.ReferenceCountUtil

/**
 * 应答消息解析器，将JT808编解码器解码后的消息交给该类进行处理&分类
 *
 * @author male
 * */
class SyncParser(private val syncMessageListener: SyncMessageListener<AbstractToStringJoiner>) {

    /**
     * 解析字节流
     *
     * */
    fun parse(buf: ByteBuf){
        try {
            val message: Message<AbstractToStringJoiner> = Message.decode(buf, MessageMetadata.outbounds(), DefaultAttributeMap())
            if (BuildConfig.DEBUG) {
                LogUtils.d("【解析】:$message")
            } else {
                LogUtils.file("【解析】:$message")
            }
            when(val payload:Any = message.body){
                is B8001 -> syncMessageListener.onCommonResponse(payload)
                is B8100 -> syncMessageListener.onSignUp(payload)
                is B8103 -> syncMessageListener.onDeviceSetting(payload)
            }
        } catch (e: Exception) {
            if (BuildConfig.DEBUG) {
                LogUtils.e("parse received data error:${e.message}")
            } else {
                LogUtils.file("parse received data error:${e.message}")
            }
        }finally {
            ReferenceCountUtil.release(buf)
        }
    }
}