package eu.eudat.logic.managers;

import eu.eudat.logic.builders.model.models.ResearcherBuilder;
import eu.eudat.data.entities.Researcher;
import eu.eudat.logic.proxy.config.ExternalUrlCriteria;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.logic.utilities.helpers.ListHelper;
import eu.eudat.models.data.external.ExternalSourcesItemModel;
import eu.eudat.models.data.external.ResearchersExternalSourcesModel;
import eu.eudat.data.query.items.item.researcher.ResearcherCriteriaRequest;
import eu.eudat.logic.proxy.config.exceptions.HugeResultSet;
import eu.eudat.logic.proxy.config.exceptions.NoURLFound;
import eu.eudat.logic.proxy.fetching.RemoteFetcher;
import eu.eudat.models.data.security.Principal;
import eu.eudat.queryable.QueryableList;
import eu.eudat.logic.services.ApiContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * Created by ikalyvas on 2/5/2018.
 */
@Component
public class ResearcherManager {

    private ApiContext apiContext;
    private RemoteFetcher remoteFetcher;
    private ConfigLoader configLoader;

    @Autowired
    public ResearcherManager(ApiContext apiContext, ConfigLoader configLoader) {
        this.apiContext = apiContext;
        this.remoteFetcher = apiContext.getOperationsContext().getRemoteFetcher();
        this.configLoader = configLoader;
    }

    public Researcher create(eu.eudat.models.data.researcher.Researcher researcher, Principal principal) throws Exception {
        Researcher researcherEntity = researcher.toDataModel();
        researcherEntity.setCreationUser(apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId()));
        return apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().createOrUpdate(researcherEntity);
    }

    public List<eu.eudat.models.data.dmp.Researcher> getCriteriaWithExternal(ResearcherCriteriaRequest researcherCriteriaRequest, Principal principal) throws HugeResultSet, NoURLFound {

        QueryableList<eu.eudat.data.entities.Researcher> items = apiContext.getOperationsContext().getDatabaseRepository().getResearcherDao().getWithCriteria(researcherCriteriaRequest.getCriteria());
        items.where((builder, root) -> builder.equal(root.get("creationUser").get("id"), principal.getId()));
        List<eu.eudat.models.data.dmp.Researcher> researchers = items.select(item -> new eu.eudat.models.data.dmp.Researcher().fromDataModel(item));
        researchers = researchers.stream().filter(item -> item.getKey().equals("Internal")).collect(Collectors.toList());
        Map<String, String> keyToSourceMap = configLoader.getKeyToSourceMap();
        for (eu.eudat.models.data.dmp.Researcher item : researchers) {
            if (item.getKey().equals("Internal"))
                item.setTag(item.getKey());
            else
                item.setTag(keyToSourceMap.get(item.getKey()));
        }
        ExternalUrlCriteria externalUrlCriteria = new ExternalUrlCriteria(researcherCriteriaRequest.getCriteria().getName());
        List<Map<String, String>> remoteRepos = remoteFetcher.getResearchers(externalUrlCriteria,null);
        ResearchersExternalSourcesModel researchersExternalSourcesModel = new ResearchersExternalSourcesModel().fromExternalItem(remoteRepos);
        for (ExternalSourcesItemModel externalListingItem : researchersExternalSourcesModel) {
            eu.eudat.models.data.dmp.Researcher researcher = apiContext.getOperationsContext().getBuilderFactory().getBuilder(ResearcherBuilder.class)
                    .label(externalListingItem.getAbbreviation())
                    .id(externalListingItem.getId())
                    .reference(externalListingItem.getRemoteId())
                    .name(externalListingItem.getName())
                    .tag(externalListingItem.getTag())
                    .key(externalListingItem.getKey())
                    .build();
            researchers.add(researcher);
        }
        return researchers.stream().distinct().collect(Collectors.toList());
    }
}
