package com.its.pis.xnetudp.codec;

import com.its.app.AppUtils;
import com.its.app.utils.SysUtils;
import com.its.pis.config.ProcessConfig;
import com.its.pis.xnetudp.protocol.CENTER_COMM_MESSAGE;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class CenterCommServerDecoder extends MessageToMessageDecoder<DatagramPacket> {

	private ProcessConfig processConfig;

	public CenterCommServerDecoder() {
		processConfig = (ProcessConfig) AppUtils.getBean(ProcessConfig.class);
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {

		ByteBuf buf = (ByteBuf)packet.content();

		int recvBytes = buf.readableBytes();
		log.info("RECV: [{}], {} Bytes.", packet.sender(), recvBytes);

		if (buf.readableBytes() < CENTER_COMM_MESSAGE.CENTER_HEADER_SIZE) {
			log.error("RECV: UDP Message header length error: {}/{} Bytes.", recvBytes, CENTER_COMM_MESSAGE.CENTER_HEADER_SIZE);
			return;
		}

		byte[] buffer = new byte[recvBytes];
		buf.getBytes(buf.readerIndex(), buffer);

		if (this.processConfig.isCenterDump()) {
			log.info("RECV DUMP: {}", SysUtils.byteArrayToHex(buffer));
		}

		CENTER_COMM_MESSAGE msg = new CENTER_COMM_MESSAGE(buffer, packet.sender());
		out.add(msg);
	}
}
