package com.cm.central.control.startup;

import com.cm.central.control.service.client.IClientService;
import com.cm.central.control.service.clientexception.IClientExceptionService;
import com.cm.central.control.service.socket.offline.IOffLineService;
import com.cm.central.control.socket.SocketServerRunnable;
import com.cm.common.token.app.AppTokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: SocketServerStartUp
 * @Description: Socket客户端启动
 * @Author: WangGeng
 * @Date: 2020/7/28 4:50 下午
 * @Version: 1.0
 **/
@Component
@EnableScheduling
public class SocketServerStartUp implements ApplicationRunner {

    private static final Logger LOG = LoggerFactory.getLogger(SocketServerStartUp.class);
    @Autowired
    private IOffLineService offLineService;
    @Autowired
    private SocketServerRunnable socketServerRunnable;
    @Value("${socket.central-control.active:false}")
    private Boolean socketServerActive;
    @Autowired
    private IClientExceptionService clientExceptionService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (socketServerActive != null && socketServerActive) {
            new Thread(socketServerRunnable).start();
        } else {
            LOG.debug("Socket监控未激活");
        }
    }

    /**
     * 检查离线情况
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void checkOfflineClientEmail() throws Exception {
        offLineService.checkOfflineClientAndSendEmail();
    }

    /**
     * 检查客户端异常情况
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void checkClientException() {
        if (socketServerActive != null && socketServerActive) {
            LOG.debug("检测客户端异常情况");
            clientExceptionService.updateClientExceptionAndNoticeProjectLeader();
        } else {
            LOG.debug("Socket监控未激活");
        }
    }

}
