package eu.eudat.query;

import eu.eudat.data.dao.DatabaseAccessLayer;
import eu.eudat.data.entities.Lock;
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 LockQuery extends Query<Lock, UUID> {

	private UUID id;
	private UUID target;
	private UserQuery userQuery;
	private Date touchedAt;

	public UUID getId() {
		return id;
	}

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

	public UUID getTarget() {
		return target;
	}

	public void setTarget(UUID target) {
		this.target = target;
	}

	public UserQuery getUserQuery() {
		return userQuery;
	}

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

	public Date getTouchedAt() {
		return touchedAt;
	}

	public void setTouchedAt(Date touchedAt) {
		this.touchedAt = touchedAt;
	}

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

	public LockQuery(DatabaseAccessLayer<Lock, UUID> databaseAccessLayer) {
		super(databaseAccessLayer);
	}

	@Override
	public QueryableList<Lock> getQuery() {
		QueryableList<Lock> query = this.databaseAccessLayer.asQueryable();
		if (this.id != null) {
			query.where((builder, root) -> builder.equal(root.get("id"), this.id));
		}
		if (this.target != null) {
			query.where(((builder, root) -> builder.equal(root.get("target"), this.target)));
		}
		if (this.userQuery != null) {
			Subquery<UserInfo> userSubQuery = this.userQuery.getQuery().query(Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id")));
			query.where((builder, root) -> root.get("lockedBy").get("id").in(userSubQuery));
		}
		return query;
	}
}
