package com.its.op.xnetudp.codec;

import com.its.utils.SysUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.List;

@Slf4j
public class VmsServerRequestEncoder extends MessageToMessageEncoder<Object> {

	private String remoteIpAddr;
	private int remotePort;

	public VmsServerRequestEncoder(String hostIp, int hostPort) {
		this.remoteIpAddr = hostIp;
		this.remotePort = hostPort;
	}

	@Override
	protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) {

		Channel channel = ctx.channel();
		if (!channel.isOpen()) {
			log.error("SEND: Channel Closed.");
		}
		if (!channel.isActive()) {
			log.error("SEND: Channel InActive.");
			channel.flush();
			return;
		}

		if (!(msg instanceof ByteBuffer)) {
			log.error("SEND: Encoding Data source Unknown Type.");
			return;
		}

		int sendBytes = ((ByteBuffer) msg).array().length;
		if (this.remoteIpAddr == null) {
			log.error("SEND: [ERROR], RemoteAddress null, {} Bytes.", sendBytes);
			return;
		}
		else {
			log.info("SEND: [{}:{}], {} Bytes.", this.remoteIpAddr, this.remotePort, sendBytes);
		}

		log.info("SEND DUMP: {}", SysUtils.byteArrayToHex(((ByteBuffer) msg).array()));

		ByteBuf byteBuf = Unpooled.buffer(sendBytes);
		byteBuf.writeBytes(((ByteBuffer) msg).array());
		InetSocketAddress addr = new InetSocketAddress(this.remoteIpAddr, this.remotePort);
		DatagramPacket packet = new DatagramPacket(byteBuf, addr);
		out.add(packet);
	}
}
