package com.its.pis.xnetudp.handler;

import com.its.app.AppUtils;
import com.its.app.utils.NettyUtils;
import com.its.pis.xnetudp.protocol.CENTER_COMM_MESSAGE;
import com.its.pis.xnetudp.thread.AbstractCenterCommServerReceiver;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class CenterCommServerPacketHandler extends SimpleChannelInboundHandler<Object> {

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

		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);
		AbstractCenterCommServerReceiver handler = (AbstractCenterCommServerReceiver) AppUtils.getBean("centerCommServerReceiver");
		if (handler != null) {
			handler.run((CENTER_COMM_MESSAGE) msg);
		}
	}

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

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
	{
		InetSocketAddress remoteAddress = (InetSocketAddress)ctx.channel().remoteAddress();
        String ip = remoteAddress.getAddress().getHostAddress();
        log.error("CenterCommServerPacketHandler::exceptionCaught: {}, {}", ip, cause.getMessage());
	    cause.printStackTrace();
	    super.exceptionCaught(ctx, cause);
	}
}
