package com.cisdi.data.AMETEKSurfaceVision.gateway;

import com.cisdi.data.sdk.gateway.netty.IoSession;
import com.cisdi.data.sdk.gateway.netty.SessionFactory;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 保活时间检测，如果超过指定时间，则关闭连接
 * @author tzz
 *
 */
@Slf4j
public class SurfaceVisionAliveCheckTask implements Runnable {
	
    private SessionFactory sessionFactory;
    private AtomicBoolean shouldRun = null;

    /**
     * 会话允许的保活时间，单位秒
     */
	private int keepAlive;
    
    private static final double multiply = 2;
    
    private static final int sleepInternal = 1000; // 1秒
    
	public SurfaceVisionAliveCheckTask(int keepAlive, AtomicBoolean shouldRun, SessionFactory sessionFactory) {
		super();
		this.keepAlive = keepAlive;
		this.shouldRun = shouldRun;
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public void run() {
		log.info("启动SurfaceVision心跳及检测心跳线程");
		
		while (shouldRun != null && shouldRun.get() == true) {
			try {
				long now = System.currentTimeMillis();
				
				List<IoSession> sessions = sessionFactory.getSessions();
				
				for (IoSession ioSession : sessions) {
					SurfaceVisionIoSession session = (SurfaceVisionIoSession)ioSession;
					log.info("{} 定时心跳发送检测", session.gwPrefix());
					session.sendBeat();
					
					// 超出指定倍数心跳时间，关闭通道
					if((now - session.getLastAliveTime()) > (multiply * keepAlive * 1000)) {
						session.close();
						log.warn("{} 超出指定倍数{}心跳时间{},单位秒，关闭通道",
								session.gwPrefix(), multiply, keepAlive);
					}
				}
				
				Thread.sleep(sleepInternal);				
			} catch (Exception e) {
				log.warn(e.getLocalizedMessage(), e);
			}
		}
		
		log.info("结束SurfaceVision保活超时检测线程");
	}
}
