package eu.eudat.logic.managers;

import eu.eudat.data.dao.criteria.DataManagementPlanCriteria;
import eu.eudat.data.dao.criteria.DatasetCriteria;
import eu.eudat.data.dao.criteria.OrganisationCriteria;
import eu.eudat.data.dao.criteria.GrantCriteria;
import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.dao.entities.DatasetDao;
import eu.eudat.data.dao.entities.OrganisationDao;
import eu.eudat.data.dao.entities.GrantDao;
import eu.eudat.data.entities.*;
import eu.eudat.logic.builders.model.models.RecentActivityDataBuilder;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.models.data.dashboard.recent.RecentActivity;
import eu.eudat.models.data.dashboard.recent.RecentActivityData;
import eu.eudat.models.data.dashboard.searchbar.SearchBarItem;
import eu.eudat.models.data.dashboard.statistics.DashBoardStatistics;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.searchbar.SearchBarItemType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Component
public class DashBoardManager {

    private ApiContext apiContext;
    private DatabaseRepository databaseRepository;

    @Autowired
    public DashBoardManager(ApiContext apiContext) {
        this.apiContext = apiContext;
        this.databaseRepository = apiContext.getOperationsContext().getDatabaseRepository();
    }

    public DashBoardStatistics getStatistics() {
        DashBoardStatistics statistics = new DashBoardStatistics();

        DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
        OrganisationCriteria organisationCriteria = new OrganisationCriteria();
        dataManagementPlanCriteria.setAllVersions(false);
        dataManagementPlanCriteria.setIsPublic(true);
        organisationCriteria.setPublic(true);

        List<DMP> dmps = databaseRepository.getDmpDao().getWithCriteria(dataManagementPlanCriteria).toList();
        long numberOfDatasets = 0;
        LinkedList<Grant> grants = new LinkedList<>();
        for (DMP dmp : dmps) {
            numberOfDatasets = numberOfDatasets + dmp.getDataset().stream()
                    .filter(item -> item.getStatus() == Dataset.Status.FINALISED.getValue()).count();
            grants.add(dmp.getGrant());
        }

        statistics.setTotalDataManagementPlanCount((long) dmps.size());
        statistics.setTotalDataSetCount(numberOfDatasets);
        statistics.setTotalGrantCount(grants.stream().distinct().count());
        statistics.setTotalOrganisationCount(databaseRepository.getOrganisationDao().getWithCriteria(organisationCriteria).count());

        return statistics;
    }

    public DashBoardStatistics getMeStatistics(Principal principal) {
        DashBoardStatistics statistics = new DashBoardStatistics();
        DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
        DatasetDao datasetRepository = databaseRepository.getDatasetDao();
        GrantDao grantRepository = databaseRepository.getGrantDao();
        OrganisationDao organisationRepository = databaseRepository.getOrganisationDao();
        UserInfo user = new UserInfo();
        user.setId(principal.getId());
        DatasetCriteria datasetCriteria = new DatasetCriteria();
        datasetCriteria.setAllVersions(false);
        DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
        dataManagementPlanCriteria.setAllVersions(false);
        GrantCriteria grantCriteria = new GrantCriteria();

        List<Integer> roles = new LinkedList<>();
        CompletableFuture dmpFuture = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId(), roles).countAsync()
                .whenComplete((dmpsStats, throwable) -> statistics.setTotalDataManagementPlanCount(dmpsStats));
        CompletableFuture datasetFuture = datasetRepository.getAuthenticated(datasetRepository.getWithCriteria(datasetCriteria), user, roles).countAsync()
                .whenComplete((datasetsStats, throwable) -> statistics.setTotalDataSetCount(datasetsStats));
        CompletableFuture grantFuture = grantRepository.getAuthenticated(grantRepository.getWithCriteria(grantCriteria), user).countAsync()
                .whenComplete((grantsStats, throwable) -> statistics.setTotalGrantCount(grantsStats));
        CompletableFuture orgnanisationFuture = organisationRepository.getAuthenticated(organisationRepository.asQueryable().withHint("organisationRecentActivity"), user).countAsync()
                .whenComplete((organisationStats, throwable) -> statistics.setTotalOrganisationCount(organisationStats));

        CompletableFuture.allOf(dmpFuture, datasetFuture, grantFuture, orgnanisationFuture).join();
        return statistics;
    }

    public RecentActivity getRecentActivity(Principal principal, Integer numberofactivities) {
        RecentActivity activity = new RecentActivity();
        DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
        DatasetDao datasetRepository = databaseRepository.getDatasetDao();
        GrantDao grantRepository = databaseRepository.getGrantDao();
        UserInfo user = new UserInfo();
        user.setId(principal.getId());
        DatasetCriteria datasetCriteria = new DatasetCriteria();
        datasetCriteria.setAllVersions(false);
        DataManagementPlanCriteria dataManagementPlanCriteria = new DataManagementPlanCriteria();
        dataManagementPlanCriteria.setAllVersions(false);
        GrantCriteria grantCriteria = new GrantCriteria();
        RecentActivityDataBuilder recentActivityDataBuilder = apiContext.getOperationsContext().getBuilderFactory().getBuilder(RecentActivityDataBuilder.class);

        List<Integer> roles = new LinkedList<>();
        CompletableFuture<List<RecentActivityData>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.getWithCriteria(dataManagementPlanCriteria), principal.getId(), roles)
                .withHint("dmpRecentActivity")
                .orderBy((builder, root) -> builder.desc(root.get("modified")))
                .take(numberofactivities)
                .selectAsync(item -> recentActivityDataBuilder.label(item.getLabel()).timestamp(item.getModified()).id(item.getId().toString()).build())
                .whenComplete((dmpActivities, throwable) -> activity.setRecentDmpActivities(dmpActivities));

        CompletableFuture<List<RecentActivityData>> datasets = datasetRepository.getAuthenticated(datasetRepository.getWithCriteria(datasetCriteria), user, roles)
                .withHint("datasetRecentActivity")
                .orderBy((builder, root) -> builder.desc(root.get("modified")))
                .take(numberofactivities)
                .selectAsync(item -> recentActivityDataBuilder.label(item.getLabel()).timestamp(item.getModified()).id(item.getId().toString()).build())
                .whenComplete((datasetActivities, throwable) -> activity.setRecentDatasetActivities(datasetActivities));

        CompletableFuture<List<RecentActivityData>> grants = grantRepository.getAuthenticated(grantRepository.getWithCriteria(grantCriteria), user)
                .withHint("grantRecentActivity")
                .orderBy((builder, root) -> builder.desc(root.get("modified")))
                .take(numberofactivities)
                .selectAsync(item -> recentActivityDataBuilder.label(item.getLabel()).timestamp(item.getModified()).id(item.getId().toString()).build())
                .whenComplete((grantActivities, throwable) -> activity.setRecentGrantActivities(grantActivities));

        CompletableFuture.allOf(grants, dmps, datasets).join();
        return activity;
    }

    public List<SearchBarItem> searchUserData(String like, Principal principal) {
        UserInfo user = new UserInfo();
        user.setId(principal.getId());
        DMPDao dataManagementPlanRepository = databaseRepository.getDmpDao();
        DatasetDao datasetRepository = databaseRepository.getDatasetDao();
        GrantDao grantRepository = databaseRepository.getGrantDao();

        List<Integer> roles = new LinkedList<>();
        List<SearchBarItem> searchBarItems = new LinkedList<>();

        CompletableFuture<List<SearchBarItem>> publicDmps = dataManagementPlanRepository.asQueryable()
                .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%"))
                .where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue()))
                .where((builder, root) -> builder.equal(root.get("isPublic"), true))
                .orderBy((builder, root) -> builder.desc(root.get("modified")))
                .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DMP.getValue(), true))
                .whenComplete((dmpItems, throwable) -> searchBarItems.addAll(dmpItems));

        CompletableFuture<List<SearchBarItem>> publicDatasets = datasetRepository.asQueryable()
                .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%"))
                .where((builder, root) -> builder.equal(root.get("status"), Dataset.Status.FINALISED.getValue()))
                .where((builder, root) -> builder.equal(root.get("dmp").get("isPublic"), true))
                .orderBy((builder, root) -> builder.desc(root.get("modified")))
                .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DATASET.getValue(), true))
                .whenComplete((dataSetItems, throwable) -> searchBarItems.addAll(dataSetItems));

        if (principal.getId() != null) {
            CompletableFuture<List<SearchBarItem>> dmps = dataManagementPlanRepository.getAuthenticated(dataManagementPlanRepository.asQueryable(), principal.getId(), roles)
                    .withHint("dmpRecentActivity")
                    .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%"))
                    .where((builder, root) -> builder.notEqual(root.get("status"), DMP.DMPStatus.DELETED.getValue()))
                    .orderBy((builder, root) -> builder.desc(root.get("modified")))
                    .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DMP.getValue(), false))
                    .whenComplete((dmpItems, throwable) -> searchBarItems.addAll(dmpItems));

            CompletableFuture<List<SearchBarItem>> datasets = datasetRepository.getAuthenticated(datasetRepository.asQueryable(), user, roles)
                    .withHint("datasetRecentActivity")
                    .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%"))
                    .where((builder, root) -> builder.notEqual(root.get("status"), Dataset.Status.DELETED.getValue()))
                    .where((builder, root) -> builder.notEqual(root.get("status"), Dataset.Status.CANCELED.getValue()))
                    .orderBy((builder, root) -> builder.desc(root.get("modified")))
                    .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.DATASET.getValue(), false))
                    .whenComplete((dataSetItems, throwable) -> searchBarItems.addAll(dataSetItems));

            CompletableFuture<List<SearchBarItem>> grants = grantRepository.getAuthenticated(grantRepository.asQueryable(), user)
                    .withHint("grantRecentActivity")
                    .where((builder, root) -> builder.like(builder.upper(root.get("label")), "%" + like.toUpperCase() + "%"))
                    .orderBy((builder, root) -> builder.desc(root.get("modified")))
                    .selectAsync(item -> new SearchBarItem(item.getId().toString(), item.getLabel(), SearchBarItemType.GRANT.getValue(), false))
                    .whenComplete((grantItems, throwable) -> searchBarItems.addAll(grantItems));

            CompletableFuture.allOf(grants, dmps, datasets, publicDmps, publicDatasets).join();
        } else {
            CompletableFuture.allOf(publicDmps, publicDatasets).join();
        }

        return searchBarItems;
    }
}
