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.PackerConfigRepository;
import cn.reghao.devops.web.mgr.builds.model.po.DockerRegistry;
import cn.reghao.devops.web.mgr.builds.model.po.PackerConfig;
import cn.reghao.devops.web.mgr.build.chain.BuildTools;
import cn.reghao.devops.common.msg.constant.PackType;
import cn.reghao.devops.web.mgr.builds.service.PackerConfigService;
import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.jutil.jdk.result.ResultStatus;
import org.springframework.stereotype.Service;

/**
 * @author reghao
 * @date 2021-09-17 15:54:16
 */
@Service
public class PackerConfigServiceImpl implements PackerConfigService {
    private final PackerConfigRepository packerConfigRepository;
    private final AppBuildQuery appBuildQuery;

    public PackerConfigServiceImpl(PackerConfigRepository packerConfigRepository, AppBuildQuery appBuildQuery) {
        this.packerConfigRepository = packerConfigRepository;
        this.appBuildQuery = appBuildQuery;
    }

    @Override
    public Result addOrModify(PackerConfig packerConfig) {
        String type = packerConfig.getType();
        if (type.equals(PackType.zip.getName())) {
            packerConfig.setTargetPath("/");
        }

        DockerRegistry dockerRegistry = packerConfig.getDockerRegistry();
        if (dockerRegistry == null) {
            return Result.result(ResultStatus.FAIL, "DockerRegistry 不存在");
        }

        String name = packerConfig.getName();
        PackerConfig entity = packerConfigRepository.findByName(name);
        if (entity == null) {
            packerConfigRepository.save(packerConfig);
            return Result.result(ResultStatus.SUCCESS);
        }

        packerConfig.setEntity(entity);
        BuildTools.removeCodePacker(packerConfig.getName());
        packerConfigRepository.save(packerConfig);
        return Result.result(ResultStatus.SUCCESS);
    }

    @Override
    public Result delete(PackerConfig packerConfig) {
        packerConfigRepository.delete(packerConfig);
        BuildTools.removeCodePacker(packerConfig.getName());
        return Result.result(ResultStatus.SUCCESS);
    }
}
