package eu.eudat.query;

import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.entities.Grant;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.types.FieldSelectionType;
import eu.eudat.queryable.types.SelectionField;

import javax.persistence.criteria.Subquery;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class GrantQuery extends Query<Grant, UUID> {

	private UUID id;
	private List<UUID> ids;
	private String label;
	private List<Integer> statuses;
	private Date created;
	private Date modified;
	private UserQuery userQuery;

	public GrantQuery(DatabaseAccessLayer<Grant, UUID> databaseAccessLayer) {
		super(databaseAccessLayer);
	}

	public GrantQuery(DatabaseAccessLayer<Grant, UUID> databaseAccessLayer, List<String> selectionFields) {
		super(databaseAccessLayer, selectionFields);
	}

	public UUID getId() {
		return id;
	}

	public void setId(UUID id) {
		this.id = id;
	}

	public List<UUID> getIds() {
		return ids;
	}

	public void setIds(List<UUID> ids) {
		this.ids = ids;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public List<Integer> getStatuses() {
		return statuses;
	}

	public void setStatuses(List<Integer> statuses) {
		statuses = statuses;
	}

	public Date getCreated() {
		return created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}

	public Date getModified() {
		return modified;
	}

	public void setModified(Date modified) {
		this.modified = modified;
	}

	public UserQuery getUserQuery() {
		return userQuery;
	}

	public void setUserQuery(UserQuery userQuery) {
		this.userQuery = userQuery;
	}

	@Override
	public QueryableList<Grant> getQuery() {
		QueryableList<Grant> query = this.databaseAccessLayer.asQueryable();
		if (this.id != null)
			query.where((builder, root) -> builder.equal(root.get("id"), this.id));
		if (this.ids != null && !this.ids.isEmpty())
			query.where((builder, root) -> root.get("id").in(this.ids));
		if (this.getStatuses() != null && !this.getStatuses().isEmpty())
			query.where((builder, root) -> root.get("status").in(this.getStatuses()));
		if (this.userQuery != null) {
			Subquery<UserInfo> userInfoSubQuery = this.userQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id")));
			query.where((builder, root) -> root.get("creationUser").get("id").in(userInfoSubQuery));
		}
		if (!this.getSelectionFields().isEmpty() && this.getSelectionFields() != null) {
			query.withFields(this.getSelectionFields());
		}
		return query;
	}
}
