package com.yeejoin.amos.iec104.tcp.server;

import org.springframework.util.ObjectUtils;

import com.yeejoin.amos.iec104.tcp.entity.Apdu;
import com.yeejoin.amos.iec104.tcp.server.session.Session;
import com.yeejoin.amos.iec104.tcp.server.session.SessionManager;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class IEC104ServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {		
		super.channelRead(ctx, msg);
		if (msg instanceof Apdu) {
			Apdu apdu = (Apdu) msg;
			receive(apdu, ctx);
		}
	}
	
	private void receive(Apdu apdu, ChannelHandlerContext ctx) {
		Session session = SessionManager.getInstance().getSession(ctx);
		if (ObjectUtils.isEmpty(session)) {
			session = SessionManager.getInstance().createSession(ctx);
		}
		session.process(apdu);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
		SessionManager.getInstance().removeSession(ctx);
	}
	
	
}
