package com.pwt.netty.handler.codec.charger;

import com.pwt.netty.common.charger.*;
import com.pwt.netty.handler.codec.exceptions.ProtocolException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 充电机协议Decoder
 */
@Slf4j
public class ChargerProtocolDecoder extends MessageToMessageDecoder<ByteBuf> {

    @SuppressWarnings("unchecked")
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
        ChargerMessage message;

        byte type = buf.getByte(0);

        Class<? extends MessageData> dataClass = ChargerMessage.MESSAGE_DATA_TYPE_MAP.get(type);
        if(dataClass == null) {
            throw new ProtocolException("invalid message type: " + type);
        }
        MessageData data = dataClass.newInstance();
        byte end = buf.getByte(buf.readableBytes() -1);
        if(end != data.getEnd()) {
            throw new ProtocolException("invalid message end");
        }

        if(data instanceof RequestData) {
            message = new RequestMessage();
        } else {
            message = new ResponseMessage();
        }
        message.setMessageData(data);
        message.decode(buf);
        out.add(message);
    }
}
