package eu.eudat.data.query.items.table.dataset;

import eu.eudat.data.dao.criteria.DatasetCriteria;
import eu.eudat.data.entities.Dataset;
import eu.eudat.data.query.definition.TableQuery;
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 DatasetTableRequest extends TableQuery<DatasetCriteria, eu.eudat.data.entities.Dataset, UUID> {
    @Override
    public QueryableList<Dataset> applyCriteria() {
        QueryableList<Dataset> 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().getStatus() != null)
            query.where((builder, root) -> builder.equal(root.get("status"), this.getCriteria().getStatus()));
        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().getAllVersions())
            query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("dmp").get("version"), query.<String>subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("dmp").get("groupId"), nestedRoot.get("dmp").get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.COMPOSITE_FIELD, "dmp:version")), String.class)));
        if (this.getCriteria().getDmpIds() != null && !this.getCriteria().getDmpIds().isEmpty())
            query.where((builder, root) -> root.get("dmp").get("id").in(this.getCriteria().getDmpIds()));
        query.where((builder, root) -> builder.equal(root.get("status"), Dataset.Status.FINALISED));
        return query;
    }

    @Override
    public QueryableList<Dataset> applyPaging(QueryableList<Dataset> items) {
        return null;
    }
}
