package com.waytous.anticollision.tcp

import com.blankj.utilcode.util.LogUtils
import com.waytous.anticollision.BuildConfig
import com.waytous.anticollision.utils.logd
import io.github.toggery.jt808.codec.Codec
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.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())
            logd("【解析】:$message")
            when(val payload:Any = message.body){
                is B8100 -> syncMessageListener.onSignUp(payload)
                is B8001 -> syncMessageListener.onCommonResponse(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)
        }
    }
}