package eu.eudat.logic.managers;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.dao.criteria.DataRepositoryCriteria;
import eu.eudat.logic.proxy.config.ExternalUrlCriteria;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.publication.PublicationModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class PublicationManager {
    private ApiContext apiContext;

    @Autowired
    public PublicationManager(ApiContext apiContext) {
        this.apiContext = apiContext;
    }

    public List<PublicationModel> getPublications(String query, String type) throws HugeResultSet, NoURLFound {
        ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(query);
        List<Map<String, String>> remoteRepos = this.apiContext.getOperationsContext().getRemoteFetcher().getPublications(externalUrlCriteria, type);

        DataRepositoryCriteria criteria = new DataRepositoryCriteria();
        if (!query.isEmpty()) criteria.setLike(query);

        List<PublicationModel> publicationModels = new LinkedList<>();

        ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        publicationModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, PublicationModel.class)).collect(Collectors.toList()));
//        publicationModels = publicationModels.stream().filter(publicationModel -> publicationModel.getName().toLowerCase().contains(query.toLowerCase())).collect(Collectors.toList());
        return publicationModels;
    }
}
