package eu.eudat.logic.managers;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.dao.criteria.RegistryCriteria;
import eu.eudat.data.entities.Registry;
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.registries.RegistryModel;
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;

@Component
public class RegistryManager {

    private ApiContext apiContext;

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

    public Registry create(RegistryModel registryModel, Principal principal) throws Exception {
        if (registryModel.getLabel() == null || registryModel.getAbbreviation() == null || registryModel.getUri() == null) {
            throw new Exception("Missing mandatory entity.");
        }
        Registry registry = registryModel.toDataModel();
        registry.getCreationUser().setId(principal.getId());
        return apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao().createOrUpdate(registry);
    }

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

        RegistryCriteria criteria = new RegistryCriteria();
        if (!query.isEmpty()) criteria.setLike(query);
        criteria.setCreationUserId(principal.getId());
        List<RegistryModel> registryModels = new LinkedList<>();
        if (type.equals("")) {
            List<Registry> registryList = (this.apiContext.getOperationsContext().getDatabaseRepository().getRegistryDao().getWithCriteria(criteria)).toList();
            registryModels = registryList.stream().map(item -> new RegistryModel().fromDataModel(item)).collect(Collectors.toList());
        }
        ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        registryModels.addAll(remoteRepos.stream().map(item -> mapper.convertValue(item, RegistryModel.class)).collect(Collectors.toList()));

        return registryModels;
    }
}
