package net.northking.cctp.daemon.schedule;

import com.alibaba.fastjson.JSON;
import net.northking.cctp.daemon.config.DaemonProperties;
import net.northking.cctp.daemon.service.DaemonService;
import net.northking.cctp.daemon.service.RobotProcess;
import net.northking.cctp.daemon.service.ScriptEngineProcess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


/**
 * 守护： 脚本引擎
 */
@Component
public class ScriptEngineSchedule
{
  private static final Logger logger = LoggerFactory.getLogger(ScriptEngineSchedule.class);

  /**
   * 初始延迟时间 5 秒，单位：毫秒。（系统启动后开始算，第一次执行的时间延迟 N 毫秒）
   */
  private static final long INITIAL_DELAY = 10 * 1000L;

  /**
   * 上一次执行结束时间点之后 60秒再执行
   */
  public static final long FIXED_DELAY = 60 * 1000L;

  private ScriptEngineProcess scriptEngine;
  private RobotProcess robotProcess;

  /**
   * 配置参数
   */
  private final DaemonProperties properties;

  private final RestTemplate restTemplate;

  private final DaemonService daemonService;

  public ScriptEngineSchedule(DaemonProperties daemonProperties, RestTemplate restTemplate, DaemonService daemonService)
  {
    this.properties = daemonProperties;
    this.restTemplate = restTemplate;
    this.daemonService = daemonService;

    this.scriptEngine = new ScriptEngineProcess(daemonProperties, restTemplate, daemonService);
    this.robotProcess=new RobotProcess(daemonProperties, restTemplate, daemonService);
  }


  /**
   * 定时校验引擎进程状态
   */
  @Scheduled(initialDelay = INITIAL_DELAY, fixedDelay = FIXED_DELAY)
  public void execute()
  {
    boolean check = false;
    if (scriptEngine.isStarted())
    {
      if (!scriptEngine.alive())
      {
        check=true;
        logger.info("【脚本引擎】进程 PID={} 未响应。", scriptEngine.getPid());
        scriptEngine.shutdown();
        scriptEngine.start();
      }
    } else
    {
      check=true;
      logger.info("【脚本引擎】进程 未启动。尝试启动！");
      scriptEngine.start();
      logger.info("【脚本引擎】进程 启动成功。更新引擎信息！");
      scriptEngine.alive();
    }
    //校验是否时更新等待时关闭-关闭机器人并更改为更新流程继续
    if(check && daemonService.preparedWaitEngine()){
      daemonService.updateToDownload();
    }
  }

  /**
   * 定时校验引擎版本是否更新
   * 如果更新完成则进行重启
   */
  @Scheduled(fixedDelay = FIXED_DELAY)
  public void restartEngine()
  {
    logger.info("引擎更新重启检查 --------- 当前状态：{}",daemonService.getInfo().getStatus());
    //查看引擎是否处于更新包解压完毕状态
    if (daemonService.preparedWaitEngine()){
      logger.info("引擎更新重启检查 ------- 检查到版本更新，jar包已下载并解压  通知引擎重启");
      //停止引擎-等待引擎守护启动新的引擎进程
      scriptEngine.stop();
      //更新状态等待引擎自己关闭重启引擎
    }
  }

  /**
   * 信息打印
   */
  @Scheduled(initialDelay = 3*1000, fixedDelay = FIXED_DELAY)
  public void infoPrintln(){
    logger.info("常规检查 ---------- 守护进程信息打印:"+ JSON.toJSON(daemonService.getInfo()));
  }


}
