package eu.eudat.logic.mapper.elastic.criteria;

import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.entities.Grant;
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 java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

public class DmpCriteriaMapper {

	public static DmpCriteria toElasticCriteria(DataManagementPlanCriteria criteria, UUID principalID) {
		DmpCriteria elastic = new DmpCriteria();

		elastic.setAllowAllVersions(criteria.getAllVersions());
		elastic.setCollaborators(criteria.getCollaborators());
		if (criteria.getGrants() != null) {
			elastic.setGrants(criteria.getGrants().stream().map(Grant::getId).collect(Collectors.toList()));
		}
		elastic.setGroupIds(criteria.getGroupIds());
		elastic.setLike(criteria.getLike());
		if (criteria.getOrganisations() != null) {
			elastic.setOrganizations(criteria.getOrganisations().stream().map(UUID::fromString).collect(Collectors.toList()));
		}
		elastic.setPublic(criteria.getIsPublic());
		if (!elastic.isPublic()) {
			elastic.setCollaborators(Collections.singletonList(principalID));
		}
		if (criteria.getRole() != null) {
			elastic.setRoles(Collections.singletonList(criteria.getRole()));
		}
		if (criteria.getStatus() != null) {
			elastic.setStatus(criteria.getStatus().shortValue());
		}
		elastic.setTemplates(criteria.getDatasetTemplates());
		elastic.setGrantStatus(criteria.getGrantStatus());
		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;
	}
}
