package cn.reghao.autodop.dmaster.app.db.query.config.impl;

import cn.reghao.autodop.dmaster.app.db.query.config.AppConfigQuery;
import cn.reghao.autodop.dmaster.app.db.repository.config.AppConfigRepository;
import cn.reghao.autodop.dmaster.app.model.po.config.AppConfig;
import cn.reghao.autodop.dmaster.app.model.po.config.build.CompilerConfig;
import cn.reghao.autodop.dmaster.app.model.po.config.build.PackerConfig;
import cn.reghao.autodop.dmaster.app.model.po.config.build.RepoAuthConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author reghao
 * @date 2021-06-02 15:01:18
 */
@Service
public class AppConfigQueryImpl implements AppConfigQuery {
    private final AppConfigRepository appRepository;

    public AppConfigQueryImpl(AppConfigRepository appRepository) {
        this.appRepository = appRepository;
    }

    @Override
    public AppConfig findById(int id) {
        return appRepository.getOne(id);
    }

    @Override
    public List<AppConfig> query(Map<String, String> kv) {
        Specification<AppConfig> specification = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            kv.forEach((name, value) -> {
                predicates.add(cb.like(root.get(name), "%" + value + "%"));
            });

            // select * from app_building where app_id like '%test%' and app_name like '%测试%'
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return appRepository.findAll(specification);
    }

    @Override
    public AppConfig findByAppId(String appId) {
        return appRepository.findByIsDeleteFalseAndAppId(appId);
    }

    @Override
    public AppConfig findByIsDeleteFalseAndAppId(String appId) {
        return appRepository.findByIsDeleteFalseAndAppId(appId);
    }

    @Override
    public Page<AppConfig> findByEnv(String env, Pageable pageable) {
        return appRepository.findByEnv(env, pageable);
    }

    @Override
    public List<AppConfig> findAll() {
        return appRepository.findAll();
    }

    @Override
    public List<AppConfig> findAllByRepoAuthConfig(RepoAuthConfig repoAuthConfig) {
        return appRepository.findAllByRepoAuthConfig(repoAuthConfig);
    }

    @Override
    public List<AppConfig> findAllByCompilerConfig(CompilerConfig compilerConfig) {
        return appRepository.findAllByCompilerConfig(compilerConfig);
    }

    @Override
    public List<AppConfig> findAllByPackerConfig(PackerConfig packerConfig) {
        return appRepository.findAllByPackerConfig(packerConfig);
    }
}
