package eu.eudat.data.query.items.item.dmp;

import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.query.definition.Query;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.types.FieldSelectionType;
import eu.eudat.queryable.types.SelectionField;

import java.util.Arrays;
import java.util.UUID;


public class DataManagementPlanCriteriaRequest extends Query<DataManagementPlanCriteria, DMP> {
    @Override
    public QueryableList<DMP> applyCriteria() {
        QueryableList<DMP> query = this.getQuery();
        if (this.getCriteria().getLike() != null && !this.getCriteria().getLike().isEmpty())
            query.where((builder, root) -> builder.or(
                    builder.like(builder.upper(root.get("label")), "%" + this.getCriteria().getLike().toUpperCase() + "%"),
                    builder.like(builder.upper(root.get("description")), "%" + this.getCriteria().getLike().toUpperCase() + "%")));
        if (this.getCriteria().getPeriodEnd() != null)
            query.where((builder, root) -> builder.lessThan(root.get("created"), this.getCriteria().getPeriodEnd()));
        if (this.getCriteria().getPeriodStart() != null)
            query.where((builder, root) -> builder.greaterThan(root.get("created"), this.getCriteria().getPeriodStart()));
        if (this.getCriteria().getGrants() != null && !this.getCriteria().getGrants().isEmpty())
            query.where(((builder, root) -> root.get("grant").in(this.getCriteria().getGrants())));
        if (!this.getCriteria().getAllVersions())
            query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"), query.<String>subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("groupId"), nestedRoot.get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), String.class)));
        if (this.getCriteria().getGroupIds() != null && !this.getCriteria().getGroupIds().isEmpty())
            query.where((builder, root) -> root.get("groupId").in(this.getCriteria().getGroupIds()));
        query.where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue()));
        return query;
    }
}
