package com.xydl.cac.service.impl;

import com.xydl.cac.entity.*;
import com.xydl.cac.repository.RemoteConfigRepository;
import com.xydl.cac.repository.RemoteDownloadRepository;
import com.xydl.cac.service.RemoteDownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.List;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class RemoteDownloadServiceImpl implements RemoteDownloadService {

    @Resource
    RemoteDownloadRepository repository;
    @Resource
    RemoteConfigRepository configRepository;

    @Override
    public Page<RemoteDownload> list(Integer configId, int pageNum, int pageSize) throws Exception {
        PageRequest request = PageRequest.of(pageNum - 1, pageSize);
        Specification<RemoteDownload> specification = (root, query, builder) -> {
            Predicate predicate = builder.conjunction();
            if (configId != null) {
                predicate.getExpressions().add(builder.equal(root.get("configId"), configId));
            }
            query.orderBy(builder.desc(root.get("id")));
            return predicate;
        };
        Page<RemoteDownload> result = repository.findAll(specification, request);
        this.fillOtherNames(result.getContent());
        return result;
    }

    private void fillOtherNames(List<RemoteDownload> list) {
        List<RemoteConfig> serverList = configRepository.findAll();
        if (!CollectionUtils.isEmpty(serverList) && !CollectionUtils.isEmpty(list)) {
            for (RemoteDownload item : list) {
                for (RemoteConfig server : serverList) {
                    if (server.getId().equals(item.getConfigId())) {
                        item.setServer(server);
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void add(RemoteDownload item) {
        item.setId(null);
        repository.save(item);
    }

    @Override
    public boolean exist(RemoteDownload item) {
        List<RemoteDownload> list = repository.findByConfigIdAndRemotePathAndFilename(item.getConfigId(), item.getRemotePath(), item.getFilename());
        if (CollectionUtils.isEmpty(list)) {
            return false;
        } else {
            return true;
        }
    }

}
