package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.DatasetProfileCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.DatasetProfile;
import eu.eudat.queryable.QueryableList;
import eu.eudat.queryable.types.FieldSelectionType;
import eu.eudat.queryable.types.SelectionField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Component("datasetProfileDao")
public class DatasetProfileDaoImpl extends DatabaseAccess<DatasetProfile> implements DatasetProfileDao {

    @Autowired
    public DatasetProfileDaoImpl(DatabaseService<DatasetProfile> databaseService) {
        super(databaseService);
    }

    @Override
    public QueryableList<DatasetProfile> getWithCriteria(DatasetProfileCriteria criteria) {
        QueryableList<DatasetProfile> query = getDatabaseService().getQueryable(DatasetProfile.class);
        if (criteria.getLike() != null && !criteria.getLike().isEmpty())
            query.where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + criteria.getLike().toUpperCase() + "%"));
        if (!criteria.getAllVersions())
            query.initSubQuery(String.class).where((builder, root) -> builder.equal(root.get("version"),
                    query.<String>subQueryMax((builder1, externalRoot, nestedRoot) -> builder1.equal(externalRoot.get("groupId"),
                            nestedRoot.get("groupId")), Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "version")), String.class)));
        if (criteria.getGroupIds() != null && !criteria.getGroupIds().isEmpty())
            query.where((builder, root) -> root.get("groupId").in(criteria.getGroupIds()));
        if (criteria.getFilter() != null && criteria.getUserId() != null) {
            if (criteria.getFilter().equals(DatasetProfileCriteria.DatasetProfileFilter.DMPs.getValue())) {
                query.initSubQuery(UUID.class).where((builder, root) ->
                        builder.and(root.get("id").in(
                                query.subQuery((builder1, root1) -> builder1.equal(root1.join("dmps", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), criteria.getUserId()),
                                        Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id")))),
                                builder.notEqual(root.get("id"), criteria.getUserId())));
                //query.where(((builder, root) -> builder.equal(root.join("dmps", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), criteria.getUserId())));
            }
            if (criteria.getFilter().equals(DatasetProfileCriteria.DatasetProfileFilter.Datasets.getValue())) {
                query.initSubQuery(UUID.class).where((builder, root) ->
                        builder.and(root.get("id").in(
                                query.subQuery((builder1, root1) -> builder1.equal(root1.join("dataset", JoinType.LEFT).join("dmp", JoinType.LEFT).join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), criteria.getUserId()),
                                        Arrays.asList(new SelectionField(FieldSelectionType.FIELD, "id")))),
                                builder.notEqual(root.get("id"), criteria.getUserId())));
            }
        }
        if (criteria.getStatus() != null) {
            query.where(((builder, root) -> builder.equal(root.get("status"), criteria.getStatus())));
        }
        if (criteria.getIds() != null) {
            query.where(((builder, root) -> root.get("id").in(criteria.getIds())));
        }
        if (criteria.getFinalized()) {
            query.where(((builder, root) -> builder.equal(root.get("status"), DatasetProfile.Status.FINALIZED.getValue())));
        } else {
            query.where(((builder, root) -> builder.notEqual(root.get("status"), DatasetProfile.Status.DELETED.getValue())));
        }
        if (criteria.getPeriodStart() != null)
            query.where((builder, root) -> builder.greaterThanOrEqualTo(root.get("created"), criteria.getPeriodStart()));
        return query;
    }

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

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

    @Override
    public QueryableList<DatasetProfile> getAll() {
        return getDatabaseService().getQueryable(DatasetProfile.class);
    }

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

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

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

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

    @Override
    public QueryableList<DatasetProfile> getAuthenticated(QueryableList<DatasetProfile> query, UUID principal, List<Integer> roles) {
        if (roles != null && !roles.isEmpty()) {
            query.where((builder, root) -> {
                Join userJoin = root.join("users", JoinType.LEFT);
                return builder.and(builder.equal(userJoin.join("user", JoinType.LEFT).get("id"), principal), userJoin.get("role").in(roles));
            });
        } else {
            query.where((builder, root) -> builder.equal(root.join("users", JoinType.LEFT).join("user", JoinType.LEFT).get("id"), principal));
        }

        return query;
    }
}
