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.taxonomy.TaxonomyModel;
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 TaxonomyManager {
    private ApiContext apiContext;

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

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

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

        List<TaxonomyModel> taxonomyModels = new LinkedList<>();

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