package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.GrantCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.Grant;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.queryable.QueryableList;
import eu.eudat.types.grant.GrantStateType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import schemasMicrosoftComOfficeOffice.LeftDocument;

import javax.persistence.criteria.JoinType;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Component("grantDao")
public class GrantDaoImpl extends DatabaseAccess<Grant> implements GrantDao {

    @Autowired
    public GrantDaoImpl(DatabaseService<Grant> databaseService) {
        super(databaseService);
    }

    @Override
    public QueryableList<Grant> getWithCriteria(GrantCriteria criteria) {
        QueryableList<Grant> query = getDatabaseService().getQueryable(Grant.class);
        if (criteria.getLike() != null && !criteria.getLike().isEmpty())
                    query.where((builder, root) ->
                    builder.or(builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"),
                    builder.or(builder.like(builder.upper(root.get("description")), "%" + criteria.getLike().toUpperCase() + "%"))));
        if (criteria.getPeriodEnd() != null)
            query.where((builder, root) -> builder.lessThan(root.get("enddate"), criteria.getPeriodEnd()));
        if (criteria.getPeriodStart() != null)
            query.where((builder, root) -> builder.greaterThan(root.get("startdate"), criteria.getPeriodStart()));
        if (criteria.getReference() != null)
            query.where((builder, root) -> builder.like(root.get("reference"), "%" + criteria.getReference() + "%"));
        if (criteria.getExactReference() != null)
            query.where((builder, root) -> builder.like(root.get("reference"), criteria.getExactReference()));
        if (criteria.getGrantStateType() != null) {
            if (criteria.getGrantStateType().equals(GrantStateType.FINISHED.getValue()))
                query.where((builder, root) -> builder.lessThan(root.get("enddate"), new Date()));
            if (criteria.getGrantStateType().equals(GrantStateType.ONGOING.getValue()))
                query.where((builder, root) ->
                        builder.or(builder.greaterThan(root.get("enddate"), new Date())
                                , builder.isNull(root.get("enddate"))));
        }
        if (criteria.isPublic()) {
            query.where((builder, root) -> builder.equal(root.join("dmps").get("status"), DMP.DMPStatus.FINALISED.getValue())).distinct();
        }

        if (criteria.isActive()) {
            query.where((builder, root) -> builder.notEqual(root.join("dmps").get("status"), DMP.DMPStatus.DELETED.getValue())).distinct();
        }
        if (criteria.getFunderId() != null && !criteria.getFunderId().trim().isEmpty())
            query.where((builder, root) -> builder.equal(root.get("funder").get("id"), UUID.fromString(criteria.getFunderId())));
        if (criteria.getFunderReference() != null && !criteria.getFunderReference().isEmpty())
            query.where((builder, root) -> builder.or(builder.like(root.join("funder", JoinType.LEFT).get("reference"), "%" + criteria.getFunderReference())));
        query.where((builder, root) -> builder.notEqual(root.get("status"), Grant.Status.DELETED.getValue()));
        return query;
    }

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

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

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

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

    public QueryableList<Grant> getAuthenticated(QueryableList<Grant> query, UserInfo principal) {
        query.where((builder, root) -> builder.equal(root.get("creationUser").get("id"), principal.getId())).distinct();
        return query;
    }

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

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