package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.ResearcherCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.Researcher;
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("researcherDao")
public class ResearcherDaoImpl extends DatabaseAccess<Researcher> implements ResearcherDao {

    @Autowired
    public ResearcherDaoImpl(DatabaseService<Researcher> databaseService) {
        super(databaseService);
    }

    @Override
    public QueryableList<Researcher> getWithCriteria(ResearcherCriteria criteria) {
        QueryableList<Researcher> query = asQueryable();
        if (criteria.getLike() != null && !criteria.getLike().isEmpty())
            query.where((builder, root) ->builder.or(builder.like(builder.lower(root.get("reference")), "%" + criteria.getLike().toLowerCase() + "%")));
        if (criteria.getName() != null && !criteria.getName().isEmpty())
            query.where((builder, root) ->builder.or(builder.like(builder.lower(root.get("label")), "%" + criteria.getName().toLowerCase() + "%")));
        if (criteria.getReference() != null && !criteria.getReference().isEmpty())
            query.where((builder, root) ->builder.or(builder.like(root.get("reference"), criteria.getReference())));
        if (criteria.getPeriodStart() != null)
            query.where((builder, root) -> builder.greaterThanOrEqualTo(root.get("created"), criteria.getPeriodStart()));
        return query;
    }

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

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

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

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

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

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