package com.its.op.xnetudp.handler;

import com.its.op.config.AppUtils;
import com.its.op.xnetudp.protocol.CENTER_COMM_MESSAGE;
import com.its.op.xnetudp.thread.CenterCommServerReceiver;
import com.its.utils.NettyUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;

@Slf4j
public class CenterCommServerPacketHandler extends SimpleChannelInboundHandler<Object> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) {

		if (!(msg instanceof CENTER_COMM_MESSAGE)) {
			log.error("CenterCommServerPacketHandler: Received Data Unknown Type: {}", NettyUtils.getTcpAddress(ctx.channel()));
			return;
		}

		// UDP 통신은 스레드 풀로 처리한다.
		CenterCommServerReceiver handler = (CenterCommServerReceiver) AppUtils.getBean(CenterCommServerReceiver.class);
		if (handler != null) {
			handler.run((CENTER_COMM_MESSAGE) msg);
		}
		else {
			log.error("CenterCommServerReceiver bean loading failed....");
		}
	}

	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.channel().flush();
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws RuntimeException {
		InetSocketAddress remoteAddress = (InetSocketAddress)ctx.channel().remoteAddress();
        String ip = remoteAddress.getAddress().getHostAddress();
        log.error("CenterCommServerPacketHandler::exceptionCaught: {}, {}", ip, cause.getMessage());
	    cause.printStackTrace();
		try {
			super.exceptionCaught(ctx, cause);
		} catch (IOException ie) {
			// FOR KISA Secure Coding pass
			log.error("exceptionCaught: IOException, permitAll");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
