package cn.reghao.bnt.web.devops.build.service.impl;

import cn.reghao.bnt.common.msg.constant.PackType;
import cn.reghao.bnt.web.devops.app.db.query.AppBuildQuery;
import cn.reghao.bnt.web.devops.build.db.repository.PackerConfigRepository;
import cn.reghao.bnt.web.devops.build.model.po.DockerRegistry;
import cn.reghao.bnt.web.devops.build.model.po.PackerConfig;
import cn.reghao.bnt.web.devops.build.service.PackerConfigService;
import cn.reghao.bnt.web.devops.builder.chain.BuildTools;
import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.jutil.jdk.web.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 addOrUpdate(PackerConfig packerConfig) {
        String type = packerConfig.getType();
        if (type.equals(PackType.zip.getName())) {
            packerConfig.setTargetPath("/");
        }

        DockerRegistry dockerRegistry = packerConfig.getDockerRegistry();
        if (type.equals(PackType.docker.getName()) && 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(int id) {
        PackerConfig packerConfig = packerConfigRepository.findById(id).orElse(null);
        if (packerConfig != null) {
            BuildTools.removeCodePacker(packerConfig.getName());
            packerConfigRepository.deleteById(id);
        }

        return Result.result(ResultStatus.SUCCESS);
    }
}
