package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.LockCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.Lock;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

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

@Service("LockDao")
public class LockDaoImpl  extends DatabaseAccess<Lock> implements LockDao {

	@Autowired
	public LockDaoImpl(DatabaseService<Lock> databaseService) {
		super(databaseService);
	}

	@Override
	public QueryableList<Lock> getWithCriteria(LockCriteria criteria) {
		QueryableList<Lock> query = this.getDatabaseService().getQueryable(Lock.class);
		if (criteria.getTouchedAt() != null)
			query.where((builder, root) -> builder.equal(root.get("touchedAt"), criteria.getTouchedAt()));
		if (criteria.getLockedBy() != null)
			query.where(((builder, root) -> builder.equal(root.get("lockedBy"), criteria.getLockedBy())));
		if (criteria.getTarget() != null)
			query.where(((builder, root) -> builder.equal(root.get("target"), criteria.getTarget())));
		return query;
	}

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

	@Async
	@Override
	public CompletableFuture<Lock> createOrUpdateAsync(Lock item) {
		return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item));
	}

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

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

	@Override
	public void delete(Lock item) {
		this.getDatabaseService().delete(item);
	}

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