package com.yfd.platform.component.iec104.server.master.handler;

import cn.hutool.core.util.ObjUtil;
import com.yfd.platform.component.iec104.core.*;
import com.yfd.platform.component.iec104.message.MessageDetail;
import com.yfd.platform.component.iec104.server.handler.ChannelHandlerImpl;
import com.yfd.platform.component.iec104.server.handler.DataHandler;
import com.yfd.platform.component.iec104.server.master.BootNettyClientChannel;
import com.yfd.platform.component.iec104.server.master.BootNettyClientChannelCache;
import com.yfd.platform.component.iec104.server.master.EventLoopGroupManager;
import com.yfd.platform.component.utils.OptimizedThreadPool;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class Iec104ClientHandler extends SimpleChannelInboundHandler<MessageDetail> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ChannelInboundHandlerAdapter.class);


	private DataHandler dataHandler;

	public Iec104ClientHandler(DataHandler dataHandler) {
		this.dataHandler = dataHandler;
	}


	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//------------获取当前激活的从站连接，添加到全局列表中 -----------------//
		BootNettyClientChannel Channel= new BootNettyClientChannel();
		String slave_ip=Iec104ThreadLocal.getIec104Conig().getSlaveIP();
		Channel.setCode(slave_ip);
		Channel.setChannel(ctx.channel());
		BootNettyClientChannelCache.save(ctx.channel().id().asShortText(),Channel);
		//------------------------添加完成------------------------------//

		// 启动成功后一直发启动链路命令
		ScheduledTaskPool scheduledTaskPool=new ScheduledTaskPool(ctx) ;
		Iec104ThreadLocal.setScheduledTaskPool(scheduledTaskPool);
		Iec104ThreadLocal.getScheduledTaskPool().sendStartFrame();
		Iec104ThreadLocal.setControlPool(new ControlManageUtil(ctx).setFrameAmountMax(Iec104ThreadLocal.getIec104Conig().getFrameAmountMax()));
		Iec104ThreadLocal.getControlPool().startSendFrameTask();

		Channel.setScheduledTaskPool(scheduledTaskPool);
		BootNettyClientChannelCache.remove(ctx.channel().id().asShortText());
		BootNettyClientChannelCache.save(ctx.channel().id().asShortText(),Channel);

//		if (dataHandler != null) {
//			OptimizedThreadPool threadPool = OptimizedThreadPool.getInstance();
//			threadPool.execute(() -> {
//				try {
//					dataHandler.handlerAdded(new ChannelHandlerImpl(ctx));
//				} catch (Exception e) {
//					LOGGER.error("Exception caught", e);
//				}
//			});
//			threadPool.shutdown();
//        }
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		//关闭通道时移除
		BootNettyClientChannel bootNettyChannel = BootNettyClientChannelCache.get(ctx.channel().id().asShortText());
		if(ObjUtil.isNotEmpty(bootNettyChannel)){
			bootNettyChannel.getScheduledTaskPool().stopSendCommandTask();
			EventLoopGroupManager.shutdownEventLoopGroup(bootNettyChannel.getCode());
			BootNettyClientChannelCache.remove(ctx.channel().id().asShortText());
			LOGGER.info(bootNettyChannel.getCode()+"的连接被设备关闭！");
		}
	}

	@Override
	public void channelRead0(ChannelHandlerContext ctx, MessageDetail ruleDetail104) throws IOException {
//		if (dataHandler != null) {
//			OptimizedThreadPool threadPool = OptimizedThreadPool.getInstance();
//			threadPool.execute(() -> {
//				try {
//					dataHandler.channelRead(new ChannelHandlerImpl(ctx), ruleDetail104);
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					LOGGER.error("Exception caught", e);
//				}
//			});
//			threadPool.shutdown();
//    	}
	}


}
