package eu.eudat.logic.managers;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.dao.criteria.ServiceCriteria;
import eu.eudat.data.entities.Service;
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.security.Principal;
import eu.eudat.models.data.services.ServiceModel;
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 ServiceManager {

    private ApiContext apiContext;

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

    public Service create(ServiceModel serviceModel, Principal principal) throws Exception {
        Service service = serviceModel.toDataModel();
        service.getCreationUser().setId(principal.getId());
        return apiContext.getOperationsContext().getDatabaseRepository().getServiceDao().createOrUpdate(service);
    }

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

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

        return serviceModels;
    }
}
