package com.its.api.xnetudp.codec;

import com.its.api.config.AppUtils;
import com.its.api.config.CenterCommConfig;
import com.its.api.utils.SysUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class CenterCommClientEncoder extends MessageToMessageEncoder<Object> {

	private String remoteIpAddr;
	private int remotePort;

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

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

		CenterCommConfig serverConfig = (CenterCommConfig) AppUtils.getBean(CenterCommConfig.class);

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

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

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

		log.info("SEND UDP, DUMP: {}", SysUtils.byteArrayToHex(((ByteBuffer) msg).array()));
/*
		// 브로드 캐스팅(모든 운영단말로 전송) 및 개별 메시지 응답
		UnitSystService unitSystService = (UnitSystService) AppUtils.getBean(UnitSystService.class);
		ConcurrentHashMap<String, voUnitSyst> untiSystMap = unitSystService.getUntiSystMap();
		for (Map.Entry<String, voUnitSyst> e : untiSystMap.entrySet()) {
			if (this.remoteIpAddr == null || this.remoteIpAddr.equals(e.getValue().getSYST_IP_1())) {
				try {
					ByteBuf byteBuf = Unpooled.buffer(sendBytes);
					byteBuf.writeBytes(((ByteBuffer) msg).array());
					InetSocketAddress addr = new InetSocketAddress(e.getValue().getSYST_IP_1(), e.getValue().getPRGM_PORT());
					DatagramPacket packet = new DatagramPacket(byteBuf, addr);
					out.add(packet);
					if (this.remoteIpAddr == null) {
						log.debug("SEND: [{}] [{}:{}], {} Bytes. OK....", e.getValue().getSYST_ID(), e.getValue().getSYST_IP_1(), e.getValue().getPRGM_PORT(), sendBytes);
					}
					else {
						log.info("SEND: [{}] [{}:{}], {} Bytes. OK....", e.getValue().getSYST_ID(), e.getValue().getSYST_IP_1(), e.getValue().getPRGM_PORT(), sendBytes);
					}
				} catch (Exception e2) {
					log.error("SEND: [{}] [{}:{}], {} Bytes. Failed. Exception: {}", e.getValue().getSYST_ID(), e.getValue().getSYST_IP_1(), e.getValue().getPRGM_PORT(), sendBytes, e2.toString());
				}
			}
		}*/
	}
}
