package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.ExternalDatasetCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.ExternalDataset;
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("externalDatasetDao")
public class ExternalDatasetDaoImpl extends DatabaseAccess<ExternalDataset> implements ExternalDatasetDao {

    @Autowired
    public ExternalDatasetDaoImpl(DatabaseService<ExternalDataset> databaseService) {
        super(databaseService);
    }

    @Override
    public QueryableList<ExternalDataset> getWithCriteria(ExternalDatasetCriteria criteria) {
        QueryableList<ExternalDataset> query = this.getDatabaseService().getQueryable(ExternalDataset.class);
        if (criteria.getLike() != null && !criteria.getLike().isEmpty())
            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.join("creationUser").get("id"), criteria.getCreationUserId()));
        return query;
    }

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

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

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

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

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

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