package cn.reghao.devops.web.mgr.builds.service.impl;

import cn.reghao.devops.web.mgr.app.db.query.AppBuildQuery;
import cn.reghao.devops.web.mgr.builds.db.repository.CompilerConfigRepository;
import cn.reghao.devops.web.mgr.app.model.po.config.AppConfig;
import cn.reghao.devops.web.mgr.builds.model.po.CompilerConfig;
import cn.reghao.devops.web.mgr.build.chain.BuildTools;
import cn.reghao.devops.web.mgr.builds.service.CompilerConfigService;
import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.jutil.jdk.result.ResultStatus;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2021-09-17 15:54:07
 */
@Service
public class CompilerConfigServiceImpl implements CompilerConfigService {
    private final CompilerConfigRepository compilerConfigRepository;
    private final AppBuildQuery appBuildQuery;

    public CompilerConfigServiceImpl(CompilerConfigRepository compilerConfigRepository, AppBuildQuery appBuildQuery) {
        this.compilerConfigRepository = compilerConfigRepository;
        this.appBuildQuery = appBuildQuery;
    }

    @Override
    public Result addOrModify(CompilerConfig compilerConfig) {
        String name = compilerConfig.getName();
        CompilerConfig entity = compilerConfigRepository.findByName(name);
        if (entity == null) {
            compilerConfigRepository.save(compilerConfig);
            return Result.result(ResultStatus.SUCCESS);
        }

        compilerConfig.setEntity(entity);
        Result result = checkBeforeUpdate(compilerConfig);
        if (result.getCode() == ResultStatus.SUCCESS.getCode()) {
            compilerConfigRepository.save(compilerConfig);
        }

        return result;
    }

    private Result checkBeforeUpdate(CompilerConfig compilerConfig) {
        BuildTools.removeCodeCompiler(compilerConfig.getName());
        return Result.result(ResultStatus.SUCCESS);
    }

    @Override
    public Result delete(CompilerConfig compilerConfig) {
        compilerConfigRepository.delete(compilerConfig);
        BuildTools.removeCodeCompiler(compilerConfig.getName());
        return Result.result(ResultStatus.SUCCESS);
    }

    private Result checkBeforeDelete(CompilerConfig compilerConfig) {
        List<AppConfig> apps = appBuildQuery.findAllByCompilerConfig(compilerConfig);
        if (!apps.isEmpty()) {
            List<String> ids = apps.stream().map(AppConfig::getAppId).collect(Collectors.toList());
            String msg = compilerConfig.getName() + " 删除失败, " + ids.toString() + " 等应用正在使用";
            return Result.result(ResultStatus.FAIL, msg);
        }

        BuildTools.removeCodeCompiler(compilerConfig.getName());
        return Result.result(ResultStatus.SUCCESS);
    }
}
