package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.ServiceCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.Service;
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("serviceDao")
public class ServiceDaoImpl extends DatabaseAccess<Service> implements ServiceDao {

    @Autowired
    public ServiceDaoImpl(DatabaseService<Service> databaseService) {
        super(databaseService);
    }

    @Override
    public QueryableList<Service> getWithCriteria(ServiceCriteria criteria) {
        QueryableList<Service> query = this.getDatabaseService().getQueryable(Service.class);
        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 Service createOrUpdate(Service item) {
        return this.getDatabaseService().createOrUpdate(item, Service.class);
    }

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

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

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

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

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