package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.ProjectCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.Project;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.JoinType;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Service("projectDao")
public class ProjectDaoImpl extends DatabaseAccess<Project> implements ProjectDao {

	public ProjectDaoImpl(DatabaseService<Project> databaseService) {
		super(databaseService);
	}

	@Override
	public QueryableList<Project> getWithCritetia(ProjectCriteria criteria) {
		QueryableList<Project> query = getDatabaseService().getQueryable(Project.class);
		if (criteria.getLike() != null && !criteria.getLike().isEmpty())
			query.where((builder, root) ->
					builder.or(builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"),
							builder.or(builder.like(builder.upper(root.get("description")), "%" + criteria.getLike().toUpperCase() + "%"))));
		if (criteria.getReference() != null)
			query.where((builder, root) -> builder.like(root.get("reference"), "%" + criteria.getReference() + "%"));
		if (criteria.getExactReference() != null)
			query.where((builder, root) -> builder.like(root.get("reference"), criteria.getExactReference()));
		if (criteria.getPeriodStart() != null)
			query.where((builder, root) -> builder.greaterThanOrEqualTo(root.get("startdate"), criteria.getPeriodStart()));
		query.where((builder, root) -> builder.notEqual(root.get("status"), Project.Status.DELETED.getValue()));
		return query;
	}

	public QueryableList<Project> getAuthenticated(QueryableList<Project> query, UserInfo principal) {
		query.where((builder, root) -> builder.or(builder.equal(root.get("creationUser"), principal), builder.equal(root.join("dmps", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), principal.getId()))).distinct();
		return query;
	}

	@Override
	public Project createOrUpdate(Project item) {
		return this.getDatabaseService().createOrUpdate(item, Project.class);
	}

	@Override
	public CompletableFuture<Project> createOrUpdateAsync(Project item) {
		return null;
	}

	@Override
	public Project find(UUID id) {
		return this.getDatabaseService().getQueryable(Project.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
	}

	@Override
	public Project find(UUID id, String hint) {
		throw new UnsupportedOperationException();
	}

	@Override
	public void delete(Project item) {
		throw new UnsupportedOperationException();
	}

	@Override
	public QueryableList<Project> asQueryable() {
		return this.getDatabaseService().getQueryable(Project.class);
	}
}
