package eu.eudat.data.dao.entities;

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

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

@Component("registryDao")
public class RegistryDaoImpl extends DatabaseAccess<Registry> implements RegistryDao {

    @Autowired
    public RegistryDaoImpl(DatabaseService<Registry> databaseService) {
        super(databaseService);
    }

    @Override
    public QueryableList<Registry> getWithCriteria(RegistryCriteria criteria) {
        QueryableList<Registry> query = this.getDatabaseService().getQueryable(Registry.class);
        if (criteria.getLike() != null)
            if (criteria.getLike() != null)
                query.where((builder, root) -> builder.or(
                        builder.like(builder.upper(root.get("reference")), "%" + criteria.getLike().toUpperCase() + "%"),
                        builder.equal(builder.upper(root.get("label")), criteria.getLike().toUpperCase())));
        if (criteria.getCreationUserId() != null)
            query.where((builder, root) -> builder.equal(root.get("creationUser").get("id"), criteria.getCreationUserId()));
        return query;
    }

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

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

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

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

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

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