package com.waytous.anticollision.tcp

import com.blankj.utilcode.util.LogUtils
import com.waytous.anticollision.BuildConfig
import io.github.toggery.jt808.codec.*
import io.netty.buffer.ByteBuf
import io.netty.util.DefaultAttributeMap
import io.netty.util.ReferenceCountUtil

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

    /**
     * 解析字节流
     *
     * */
    fun parse(buf: ByteBuf){
        try {
            val message: Message<Codec<*>> = Message.decode(buf, MessageMetadata.outbounds(), DefaultAttributeMap())
            when(val codec:Codec<*> = message.body){
                is B8001Codec -> syncMessageListener.onCommonResponse(codec)
                is B8100Codec -> syncMessageListener.onRegistered(codec)
            }
            LogUtils.d(message.toString())
        } 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)
        }
    }
}