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.data.entities.DataRepository;
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.datarepository.DataRepositoryModel;
import eu.eudat.models.data.license.LicenseModel;
import eu.eudat.models.data.security.Principal;
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;

/**
 * Created by ikalyvas on 9/3/2018.
 */
@Component
public class LicenseManager {
    private ApiContext apiContext;

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

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

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

        List<LicenseModel> licenseModels = new LinkedList<>();

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