package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.FunderCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.Funder;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Component("funderDao")
public class FunderDaoImpl extends DatabaseAccess<Funder> implements FunderDao {

	@Autowired
	public FunderDaoImpl(DatabaseService<Funder> databaseService) {
		super(databaseService);
	}

	@Override
	public QueryableList<Funder> getWithCritetia(FunderCriteria criteria) {
		QueryableList<Funder> query = getDatabaseService().getQueryable(Funder.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("definition")), "%" + criteria.getLike().toUpperCase() + "%"))));
		if (criteria.getReference() != null)
			query.where((builder, root) -> builder.like(builder.upper(root.get("reference")), "%" + criteria.getReference().toUpperCase() + "%"));
		if (criteria.getExactReference() != null)
			query.where((builder, root) -> builder.like(builder.upper(root.get("reference")), criteria.getExactReference().toUpperCase()));
		if (criteria.getPeriodStart() != null)
			query.where((builder, root) -> builder.greaterThanOrEqualTo(root.get("created"), criteria.getPeriodStart()));
		query.where((builder, root) -> builder.notEqual(root.get("status"), Funder.Status.DELETED.getValue()));
		return query;
	}

	@Override
	public QueryableList<Funder> getAuthenticated(QueryableList<Funder> query, UserInfo principal) {
		query.where((builder, root) -> builder.equal(root.get("creationUser"), principal));
		return query;
	}

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

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

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

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

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

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