package cn.reghao.devops.web.config;

import cn.reghao.devops.web.mgr.builds.service.BuildDirService;
import cn.reghao.devops.web.mgr.machine.service.MachineService;
import cn.reghao.devops.web.mgr.builds.db.repository.CompilerConfigRepository;
import cn.reghao.devops.web.mgr.builds.model.po.CompilerConfig;
import cn.reghao.devops.web.admin.sys.service.SysMessageService;
import cn.reghao.devops.web.ws.handler.LogHandler;
import cn.reghao.devops.web.mgr.build.model.constant.CompileType;
import cn.reghao.devops.web.mgr.log.Appenders;
import cn.reghao.devops.web.mgr.log.LoggerConfig;
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 AppLifecycle implements ApplicationRunner, DisposableBean {
    private final LogHandler logHandler;
    private final CompilerConfigRepository compilerConfigRepository;
    private final SysMessageService sysMessageService;
    private final MachineService machineService;
    private final BuildDirService buildDirService;
    private final AppProperties appProperties;

    public AppLifecycle(LogHandler logHandler, CompilerConfigRepository compilerConfigRepository,
                        SysMessageService sysMessageService, MachineService machineService,
                        BuildDirService buildDirService, AppProperties appProperties) {
        this.logHandler = logHandler;
        this.compilerConfigRepository = compilerConfigRepository;
        this.sysMessageService = sysMessageService;
        this.machineService = machineService;
        this.buildDirService = buildDirService;
        this.appProperties = appProperties;
    }

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

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

    private void initSys() throws IOException {
        initBuildDir();
        initLogConfig();
        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-web 结束运行", baseDir);
            System.exit(1);
        } else {
            try {
                buildDirService.init(baseDir);
            } catch (Exception e) {
                log.error("初始化本地构建目录失败: {}，devops-web 结束运行", e.getMessage());
                System.exit(1);
            }
        }
    }

    private void initLogConfig() {
        String app = "devops-web";
        String host = "localhost";
        LoggerConfig.initLogger(List.of(
                Appenders.pushAppender(app, host, logHandler),
                Appenders.consoleAppender()));

        /*String env = System.getProperty("spring.profiles.active");
        if ("dev".equals(env)) {
            LoggerConfig.initLogger(List.of(
                    Appenders.pushAppender(app, host, logHandler),
                    Appenders.consoleAppender()));
        } else {
            LoggerConfig.initLogger(List.of(
                    Appenders.pushAppender(app, host, logHandler),
                    Appenders.fileAppender()));
        }*/
    }

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

            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);
            }
        }
    }
}
