package eu.eudat.publicapi.criteria.mapper;

import eu.eudat.data.query.definition.helpers.ColumnOrderings;
import eu.eudat.data.query.definition.helpers.Ordering;
import eu.eudat.elastic.criteria.DmpCriteria;
import eu.eudat.elastic.criteria.SortCriteria;
import eu.eudat.publicapi.criteria.dmp.DataManagementPlanPublicCriteria;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

public class DmpPublicCriteriaMapper {

    public static DmpCriteria toElasticCriteria(DataManagementPlanPublicCriteria criteria) {
        DmpCriteria elastic = new DmpCriteria();

        elastic.setPublic(true);
        elastic.setLike(criteria.getLike());
        elastic.setAllowAllVersions(criteria.getAllVersions());
        if(criteria.getDatasetTemplates() != null) {
            elastic.setTemplates(criteria.getDatasetTemplates());
        }
        if (criteria.getGrants() != null) {
            elastic.setGrants(criteria.getGrants());
        }
        if (criteria.getCollaborators() != null) {
            elastic.setCollaborators(criteria.getCollaborators());
        }
        if (criteria.getDmpOrganisations() != null) {
            elastic.setOrganizations(criteria.getDmpOrganisations().stream().map(UUID::fromString).collect(Collectors.toList()));
        }
        if(criteria.getGroupIds() != null) {
            elastic.setGroupIds(criteria.getGroupIds());
        }

        return elastic;
    }

    public static List<SortCriteria> toElasticSorting(ColumnOrderings columnOrderings) {
        List<SortCriteria> sortCriteria = new ArrayList<>();
        if (columnOrderings.getFieldOrderings() != null && !columnOrderings.getFieldOrderings().isEmpty()) {
            for (Ordering ordering: columnOrderings.getFieldOrderings()) {
                SortCriteria sortCriteria1 = new SortCriteria();
                sortCriteria1.setFieldName(ordering.getFieldName() + (ordering.getFieldName().contains("label") ?".keyword" : ""));
                sortCriteria1.setColumnType(ordering.getColumnType() != null ? SortCriteria.ColumnType.valueOf(ordering.getColumnType().name()): SortCriteria.ColumnType.COLUMN);
                sortCriteria1.setOrderByType(SortCriteria.OrderByType.valueOf(ordering.getOrderByType().name()));
                sortCriteria.add(sortCriteria1);
            }
        }
        return sortCriteria;
    }

}
