package com.yfd.platform.component.iec104.core;

import cn.hutool.core.util.ObjUtil;
import com.yfd.platform.component.iec104.common.BasicInstruction104;
import com.yfd.platform.component.iec104.message.MessageDetail;
import com.yfd.platform.component.iec104.server.master.BootNettyClientChannel;
import com.yfd.platform.component.iec104.server.master.BootNettyClientChannelCache;
import com.yfd.platform.component.utils.OptimizedThreadPool;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 *  这是一个定时任务管理池
 * @ClassName:  ScheduledTaskPool
 * @Description:
 * @author: YDL
 * @date:   2020年5月19日 上午10:47:15
 */
@Slf4j
public class ScheduledTaskPool {

	private static final Logger LOGGER = LoggerFactory.getLogger(ChannelInboundHandlerAdapter.class);
	private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
	/**
	 * 发送指令
	 */
	private ChannelHandlerContext ctx;

	public ScheduledTaskPool(ChannelHandlerContext ctx) {
		this.ctx = ctx;
	}

	/**
	 *
	* @Title: sendStatrFrame
	* @Description: 发送启动帧
	 */
	public void sendStartFrame() {
		try {
			BootNettyClientChannel Channel= BootNettyClientChannelCache.get(ctx.channel().id().asShortText());
			if(ObjUtil.isNotEmpty(Channel)){
				ctx.channel().writeAndFlush(BasicInstruction104.STARTDT);
				String slave_ip= Channel.getCode();
				LOGGER.info(String.format("向从站[%s]发送启动链路指令！",slave_ip));
			}
		} catch (Exception e) {
			LOGGER.error("Exception caught", e);
		}
	}


	/**
	 *
	 * @Title: startTestLinkTask
	 * @Description: 启动发送测试帧任务
	 */
	public void startTestLinkTask() {
		scheduler.scheduleAtFixedRate(this::sendTestFrame, 0, 30, TimeUnit.SECONDS);
	}

	/**
	 *
	* @Title: sendTestFrame
	* @Description: 发送测试帧
	 */
	private void sendTestFrame() {
//		OptimizedThreadPool threadPool = OptimizedThreadPool.getInstance();
//		threadPool.execute(() -> {
//			try {
//				BootNettyClientChannel channel = BootNettyClientChannelCache.get(ctx.channel().id().asShortText());
//				if(ObjUtil.isNotEmpty(channel )){
//					String slaveIp = channel .getCode();
//					LOGGER.info(String.format("向从站[%s]发送测试链路指令！",slaveIp ));
//					ctx.channel().writeAndFlush(BasicInstruction104.TESTFR);
//					//对时指令
//					ctx.channel().writeAndFlush(BasicInstruction104.getTimeScale104());
//				}
//			} catch (Exception e) {
//				LOGGER.error("Exception caught", e);
//			}
//		});
//		threadPool.shutdown();
	}


	/**
	 *
	* @Title: startGeneralCallTask
	* @Description: 启动总召唤任务
	 */
	public void startGeneralCallTask() {
		scheduler.scheduleAtFixedRate(this::sendGeneralCall, 15, 45, TimeUnit.SECONDS);
	}

	private void sendGeneralCall() {
//		OptimizedThreadPool threadPool = OptimizedThreadPool.getInstance();
//		threadPool.execute(() -> {
//			try {
//				BootNettyClientChannel channel = BootNettyClientChannelCache.get(ctx.channel().id().asShortText());
//				if (ObjUtil.isNotEmpty(channel)) {
//					String slaveIp = channel.getCode();
//					MessageDetail messageDetail = BasicInstruction104.getGeneralCallRuleDetail104();
//					LOGGER.info(String.format("向从站[%s]发送总召唤指令[%s]！", slaveIp, messageDetail.getHexString()));
//					ctx.channel().writeAndFlush(messageDetail);
//				}
//			} catch (Exception e) {
//				LOGGER.error("Exception caught", e);
//			}
//		});
//		threadPool.shutdown();
	}

	public void stopSendCommandTask() {
		scheduler.shutdown();
		try {
			if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
				scheduler.shutdownNow();
			}
		} catch (InterruptedException e) {
			scheduler.shutdownNow();
			Thread.currentThread().interrupt(); // 保持中断状态
		}
	}


}
