package eu.eudat.query;

import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.Dataset;
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.List;
import java.util.UUID;

public class DatasetQuery extends Query<Dataset, UUID> {

	private UUID id;
	private String label;
	private DMPQuery dmpQuery;

	public DatasetQuery(DatabaseAccessLayer<Dataset, UUID> databaseAccessLayer) {
		super(databaseAccessLayer);
	}

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

	public UUID getId() {
		return id;
	}

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

	public String getLabel() {
		return label;
	}

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

	public DMPQuery getDmpQuery() {
		return dmpQuery;
	}

	public void setDmpQuery(DMPQuery dmpQuery) {
		this.dmpQuery = dmpQuery;
	}

	@Override
	public QueryableList<Dataset> getQuery() {
		QueryableList<Dataset> query = this.databaseAccessLayer.asQueryable();
		if (this.id != null) {
			query.where((builder, root) -> builder.equal(root.get("id"), this.id));
		}
		if (this.dmpQuery != null) {
			Subquery<DMP> dmpSubQuery = this.dmpQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id")));
			query.where((builder, root) -> root.get("dmp").get("id").in(dmpSubQuery));
		}
		return query;
	}
}
