package net.northking.cctp.daemon.service;

import com.alibaba.fastjson.JSON;
import net.northking.cctp.daemon.config.DaemonProperties;
import net.northking.cctp.daemon.config.EngineProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;

/**
 * 异步等待任务清空掉起关闭服务进程
 */
public class EngineServiceStartThread extends Thread{
    private static final Logger logger = LoggerFactory.getLogger(EngineServiceStartThread.class);

    /**
     * 配置参数
     */
    private final DaemonProperties daemonProperties;
    private final EngineProperties engineProperties;

    private final DaemonService daemonService;

    EngineServiceStartThread(DaemonProperties daemonProperties, DaemonService daemonService){
        this.daemonProperties = daemonProperties;
        this.engineProperties = daemonProperties.getEngine();
        this.daemonService = daemonService;
    }

    public void run(){
        //组装启动参数
        List<String> command = new ArrayList<>();
        command.add("java");
        command.add("-jar");
        command.add("-Xms"+engineProperties.getOpsXms());
        command.add("-Xmx"+engineProperties.getOpsXmx());
        command.add("-XX:PermSize="+engineProperties.getOpsPermSize());
        command.add("-Dloader.path=lib,modules");
        command.add("-Dfile.encoding="+engineProperties.getEncoding());
        command.add("-Dspring.config.location=config/application.yml");
        command.add(getEngineName());

        ProcessBuilder processBuilder = new ProcessBuilder().command(command);
        logger.info("文件启动路径：{}",System.getProperty("user.dir")+"/"+daemonProperties.getEngineHome());
        logger.info("command集和：{}", JSON.toJSONString(command));
        processBuilder.directory(new File(System.getProperty("user.dir")+"/"+daemonProperties.getEngineHome()));
        processBuilder.redirectErrorStream(true);
        LineNumberReader input = null;
        try {
            Process process = processBuilder.start();
            input = new LineNumberReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while (null != (line = input.readLine())) {
                logger.info("====执行引擎程序打印：{}",line);
            }
            int code = process.waitFor();
            logger.warn("====执行引擎程序关闭。。。,退出码：{}",code);
        } catch (IOException | InterruptedException e) {
            logger.error("",e);
        }
    }

    /**
     * 从文件中获取当前的引擎jar包名称
     * @return
     */
    private String getEngineName()
    {
        String jarName="";
        String jarFile = daemonProperties.getEngineHome() + "/" + engineProperties.getJarFile();
        try (Scanner sc = new Scanner(new FileReader(jarFile)))
        {
            while (sc.hasNextLine())
            {  //按行读取字符串
                jarName = sc.nextLine();
                logger.info("读取到jarName:{}", jarName);
            }
        } catch (FileNotFoundException e)
        {
            logger.error("脚本引擎的jarFile文件不存在！" + e.getMessage());
        }
        return jarName;
    }
}
