package eu.eudat.data.dao.entities;

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

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

/**
 * Created by ikalyvas on 3/21/2018.
 */
@Service("dmpProfileDao")
public class DMPProfileDaoImpl extends DatabaseAccess<DMPProfile> implements DMPProfileDao {

    @Autowired
    public DMPProfileDaoImpl(DatabaseService<DMPProfile> databaseService) {
        super(databaseService);
    }

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

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


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

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

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


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


    @Override
    public QueryableList<DMPProfile> getWithCriteria(DataManagementPlanProfileCriteria criteria) {
        QueryableList<DMPProfile> query = getDatabaseService().getQueryable(DMPProfile.class);
        if (criteria.getLike() != null && !criteria.getLike().isEmpty())
            query.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"));
        query.where(((builder, root) -> builder.notEqual(root.get("status"), DMPProfile.Status.DELETED.getValue())));
        return query;
    }
}
