package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.DataRepositoryCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.DataRepository;
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("dataRepositoryDao")
public class DataRepositoryDaoImpl extends DatabaseAccess<DataRepository> implements DataRepositoryDao {

    @Autowired
    public DataRepositoryDaoImpl(DatabaseService<DataRepository> databaseService) {
        super(databaseService);
    }

    @Override
    public QueryableList<DataRepository> getWithCriteria(DataRepositoryCriteria criteria) {
        QueryableList<DataRepository> query = this.getDatabaseService().getQueryable(DataRepository.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 DataRepository find(UUID id) {
        return this.getDatabaseService().getQueryable(DataRepository.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingle();
    }

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

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

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

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

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