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

import eu.eudat.data.dao.criteria.GrantCriteria;
import eu.eudat.data.entities.Grant;
import eu.eudat.data.query.definition.Query;
import eu.eudat.queryable.QueryableList;

public class GrantCriteriaRequest extends Query<GrantCriteria, Grant> {
    private Integer length;

    public Integer getLength() {
        return length;
    }

    public void setLength(Integer length) {
        this.length = length;
    }

    private GrantCriteriaRequest() {
    }

    @Override
    public QueryableList<Grant> applyCriteria() {
        QueryableList<Grant> 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("enddate"), this.getCriteria().getPeriodEnd()));
        if (this.getCriteria().getPeriodStart() != null)
            query.where((builder, root) -> builder.greaterThan(root.get("startdate"), this.getCriteria().getPeriodStart()));
        if (this.getCriteria().getReference() != null)
            query.where((builder, root) -> builder.equal(root.get("reference"), this.getCriteria().getReference()));
        query.where((builder, root) -> builder.notEqual(root.get("status"), Grant.Status.DELETED.getValue()));
        return query;
    }
}
