package cn.reghao.autodop.dmaster.app.service.config.impl;

import cn.reghao.autodop.dmaster.app.db.crud.config.PackerConfigCrud;
import cn.reghao.autodop.dmaster.app.db.query.config.AppConfigQuery;
import cn.reghao.autodop.dmaster.app.model.po.config.AppConfig;
import cn.reghao.autodop.dmaster.app.model.po.config.build.PackerConfig;
import cn.reghao.autodop.dmaster.app.service.config.PackerConfigService;
import cn.reghao.jdkutil.result.Result;
import cn.reghao.jdkutil.result.ResultStatus;
import org.springframework.stereotype.Service;

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

/**
 * @author reghao
 * @date 2021-09-17 15:54:16
 */
@Service
public class PackerConfigServiceImpl implements PackerConfigService {
    private final PackerConfigCrud packerConfigCrud;
    private final AppConfigQuery appConfigQuery;

    public PackerConfigServiceImpl(PackerConfigCrud packerConfigCrud, AppConfigQuery appConfigQuery) {
        this.packerConfigCrud = packerConfigCrud;
        this.appConfigQuery = appConfigQuery;
    }

    @Override
    public Result add(PackerConfig packerConfig) {
        packerConfigCrud.save(packerConfig);
        return Result.result(ResultStatus.SUCCESS);
    }

    @Override
    public Result modify(PackerConfig packerConfig) {
        packerConfigCrud.save(packerConfig);
        return Result.result(ResultStatus.SUCCESS);
    }

    @Override
    public Result delete(PackerConfig packerConfig) {
        List<AppConfig> apps = appConfigQuery.findAllByPackerConfig(packerConfig);
        if (apps.isEmpty()) {
            packerConfigCrud.delete(packerConfig);
            return Result.result(ResultStatus.SUCCESS);
        } else {
            List<String> ids = apps.stream().map(AppConfig::getAppId).collect(Collectors.toList());
            String msg = packerConfig.getName() + " 删除失败, " + ids + " 等应用正在使用";
            return Result.result(ResultStatus.FAIL, msg);
        }
    }
}
