package cn.reghao.devops.mgr.config;

import cn.reghao.devops.mgr.build.service.BuildDirService;
import cn.reghao.devops.mgr.machine.service.MachineService;
import cn.reghao.devops.mgr.build.db.repository.CompilerConfigRepository;
import cn.reghao.devops.mgr.build.model.po.CompilerConfig;
import cn.reghao.devops.mgr.admin.service.SysMessageService;
import cn.reghao.devops.mgr.builder.model.constant.CompileType;
import cn.reghao.jutil.jdk.shell.ShellExecutor;
import cn.reghao.jutil.jdk.shell.ShellResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author reghao
 * @date 2019-09-26 17:22:16
 */
@Slf4j
@Component
public class SpringLifecycle implements ApplicationRunner, DisposableBean {
    private final CompilerConfigRepository compilerConfigRepository;
    private final SysMessageService sysMessageService;
    private final MachineService machineService;
    private final BuildDirService buildDirService;
    private final AppProperties appProperties;
    private final ShellExecutor shellExecutor;

    public SpringLifecycle(CompilerConfigRepository compilerConfigRepository, SysMessageService sysMessageService,
                           MachineService machineService, BuildDirService buildDirService,
                           AppProperties appProperties, ShellExecutor shellExecutor) {
        this.compilerConfigRepository = compilerConfigRepository;
        this.sysMessageService = sysMessageService;
        this.machineService = machineService;
        this.buildDirService = buildDirService;
        this.appProperties = appProperties;
        this.shellExecutor = shellExecutor;
    }

    @Override
    public void run(ApplicationArguments args) throws IOException {
        initSys();
        log.info("devops-mgr started");
    }

    @Override
    public void destroy() {
        machineService.shutdown();
        log.info("devops-mgr shutdown...");
    }

    private void initSys() throws IOException {
        initBuildDir();
        checkCompilerConfig();
    }

    @Deprecated
    private void initBuildDir() {
        String userDir = System.getProperty("user.dir");
        String baseDir = appProperties.getBaseDir();
        File dir = new File(baseDir);
        if (!dir.exists() && !dir.mkdirs()) {
            log.error("创建本地构建目录 {} 失败，devops-mgr 结束运行", baseDir);
            System.exit(1);
        } else {
            try {
                buildDirService.init(baseDir);
            } catch (Exception e) {
                log.error("初始化本地构建目录失败，devops-mgr 结束运行");
                e.printStackTrace();
                System.exit(1);
            }
        }
    }

    private void checkCompilerConfig() {
        List<CompilerConfig> list = compilerConfigRepository.findAll();
        for (CompilerConfig compilerConfig : list) {
            if (compilerConfig.getType().equals(CompileType.none.getName())) {
                continue;
            }

            if (compilerConfig.getType().equals(CompileType.shell.getName())) {
                String versionCmd = compilerConfig.getVersionCmd();
                ShellResult shellResult = shellExecutor.exec(versionCmd.split("\\s+"));
                if (shellResult.getExitCode() != 0) {
                    String title = "编译配置异常";
                    String errMsg = shellResult.getResult();
                    sysMessageService.putSysMessage(title, errMsg);
                }
            }
            /*String name = compilerConfig.getName();
            String homePath = compilerConfig.getHomePath();
            File file = new File(homePath);
            if (!file.exists()) {
                String title = "系统异常";
                String errMsg = String.format("编译配置 %s 的编译器 %s 不存在", name, homePath);
                sysMessageService.putSysMessage(title, errMsg);
            }*/
        }
    }
}
