
package cn.orionsec.ops.service.impl;

import cn.orionsec.kit.lang.utils.Strings;
import cn.orionsec.kit.lang.utils.io.Files1;
import cn.orionsec.ops.constant.system.SystemEnvAttr;
import cn.orionsec.ops.dao.ApplicationReleaseMachineDAO;
import cn.orionsec.ops.entity.domain.ApplicationReleaseMachineDO;
import cn.orionsec.ops.service.api.ApplicationReleaseMachineService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service("applicationReleaseMachineService")
public class ApplicationReleaseMachineServiceImpl implements ApplicationReleaseMachineService {

    @Resource
    private ApplicationReleaseMachineDAO applicationReleaseMachineDAO;

    @Override
    public List<ApplicationReleaseMachineDO> getReleaseMachines(Long releaseId) {
        LambdaQueryWrapper<ApplicationReleaseMachineDO> wrapper = new LambdaQueryWrapper<ApplicationReleaseMachineDO>()
                .eq(ApplicationReleaseMachineDO::getReleaseId, releaseId);
        return applicationReleaseMachineDAO.selectList(wrapper);
    }

    @Override
    public List<ApplicationReleaseMachineDO> getReleaseMachines(List<Long> releaseIdList) {
        LambdaQueryWrapper<ApplicationReleaseMachineDO> wrapper = new LambdaQueryWrapper<ApplicationReleaseMachineDO>()
                .in(ApplicationReleaseMachineDO::getReleaseId, releaseIdList)
                .orderByAsc(ApplicationReleaseMachineDO::getId);
        return applicationReleaseMachineDAO.selectList(wrapper);
    }

    @Override
    public List<Long> getReleaseMachineIdList(List<Long> releaseIdList) {
        LambdaQueryWrapper<ApplicationReleaseMachineDO> wrapper = new LambdaQueryWrapper<ApplicationReleaseMachineDO>()
                .select(ApplicationReleaseMachineDO::getId)
                .in(ApplicationReleaseMachineDO::getReleaseId, releaseIdList)
                .orderByAsc(ApplicationReleaseMachineDO::getId);
        return applicationReleaseMachineDAO.selectList(wrapper).stream()
                .map(ApplicationReleaseMachineDO::getId)
                .collect(Collectors.toList());
    }

    @Override
    public Integer deleteByReleaseId(Long releaseId) {
        LambdaQueryWrapper<ApplicationReleaseMachineDO> machineWrapper = new LambdaQueryWrapper<ApplicationReleaseMachineDO>()
                .eq(ApplicationReleaseMachineDO::getReleaseId, releaseId);
        return applicationReleaseMachineDAO.delete(machineWrapper);
    }

    @Override
    public String getReleaseMachineLogPath(Long id) {
        return Optional.ofNullable(applicationReleaseMachineDAO.selectById(id))
                .map(ApplicationReleaseMachineDO::getLogPath)
                .filter(Strings::isNotBlank)
                .map(s -> Files1.getPath(SystemEnvAttr.LOG_PATH.getValue(), s))
                .orElse(null);
    }

}
