import { ReportType } from '../../../../../types/UserReports.js';
import DefinitionUtils from '../../../../../utils/definitionUtils.js';
import UserReportsListUtils from '../../../../../components/user-reports/utils.js';
import FiltersUtils from '../../../../../components/_filters/utils.js';
import ReportActionsUtils from '../../../../../components/_reports/report-heading/report-actions/utils.js';
import { ReportQuery } from '../../../../../types/ReportQuery.js';
import localsHelper from '../../../../../utils/localsHelper.js';
import { FiltersType } from '../../../../../components/_filters/filtersTypeEnum.js';
import { FilterType } from '../../../../../components/_filters/filter-input/enum.js';
import { validateDashboardVisualisations } from '../../../../../components/_dashboards/dashboard-visualisation/utils.js';
import { createDashboardSections } from '../../../../../components/_dashboards/dashboard-section/utils.js';
import DashboardSchema from './validate.js';
import { setUpBookmark } from '../../../../../components/bookmark/utils.js';

const setDashboardActions = (dashboardDefinition, reportDefinition, requestData) => {
    const reportName = reportDefinition.name;
    const { name } = dashboardDefinition;
    const actionsUrl = requestData?.url?.request?.fullUrl;
    const executionId = requestData?.executionId;
    let actions = {};
    if (actionsUrl) {
        actions = {
            share: {
                reportName,
                name,
                url: actionsUrl,
            },
            copy: {
                url: actionsUrl,
            },
        };
        if (executionId) {
            actions = {
                ...actions,
                refresh: {
                    url: actionsUrl,
                    executionId,
                },
            };
        }
    }
    return ReportActionsUtils.getActions(actions);
};
const getDefinitionData = async ({ req, res, services, queryData, }) => {
    const { token } = localsHelper.getValues(res);
    const { reportId, id } = req.params;
    const dataProductDefinitionsPath = req.query['dataProductDefinitionsPath'];
    // Dashboard Definition,
    const dashboardDefinition = await services.dashboardService.getDefinition(token, reportId, id, dataProductDefinitionsPath, queryData);
    // Validate definition
    DashboardSchema.DashboardSchema.parse(dashboardDefinition);
    // validate visualisations
    await validateDashboardVisualisations(dashboardDefinition);
    // Report summary data
    const reportDefinition = await DefinitionUtils.getReportSummary(reportId, services.reportingService, token, dataProductDefinitionsPath);
    // Get the filters
    const filtersData = await FiltersUtils.getFilters({
        fields: dashboardDefinition.filterFields || [],
        req,
        filtersType: FiltersType.INTERACTIVE,
    });
    const filtersQuery = FiltersUtils.setRequestQueryFromFilterValues(filtersData.filters);
    // Create the query
    const query = new ReportQuery({
        fields: dashboardDefinition.filterFields || [],
        queryParams: filtersQuery,
        definitionsPath: dataProductDefinitionsPath,
        reportType: ReportType.DASHBOARD,
    }).toRecordWithFilterPrefix(true);
    return {
        query,
        filters: filtersData,
        dashboardDefinition,
        reportDefinition,
    };
};
const updateStore = async (services, tableId, userId, sections, req, filters) => {
    const { requestedReportService } = services;
    const dashboardRequestData = await requestedReportService.getReportByTableId(tableId, userId);
    // Add to recently viewed
    if (sections && sections.length && dashboardRequestData) {
        UserReportsListUtils.updateLastViewed({
            services,
            reportStateData: dashboardRequestData,
            userId,
            req,
            filters,
        });
    }
    return dashboardRequestData;
};
const getPartialDate = (filters) => {
    let partialDate;
    const granularDateRangeFilter = (filters.find((f) => f.type === FilterType.granularDateRange.toLowerCase()));
    if (granularDateRangeFilter) {
        partialDate = granularDateRangeFilter.value.partialDate;
    }
    return partialDate;
};
const renderAsyncDashboard = async ({ req, res, services }) => {
    const { token, csrfToken, dprUser } = localsHelper.getValues(res);
    const { reportId, id, tableId } = req.params;
    const { bookmarkService, requestedReportService } = services;
    const { id: userId } = dprUser;
    let requestData = await requestedReportService.getReportByTableId(tableId, userId);
    const queryData = requestData?.query?.data;
    // Get the definition Data
    const { query, filters, reportDefinition, dashboardDefinition } = await getDefinitionData({
        req,
        res,
        services,
        queryData,
    });
    // Get the results data
    const dashboardData = await services.dashboardService.getAsyncDashboard(token, id, reportId, tableId, query);
    const flattenedData = Array.isArray(dashboardData)
        ? dashboardData.flat().filter(Boolean)
        : [];
    const partialDate = getPartialDate(filters.filters);
    const bookmarkConfig = setUpBookmark(res, req, bookmarkService);
    // Get the dashboard parts
    const dashboardFeatureFlags = res.app.locals['featureFlags'].flags;
    const sections = createDashboardSections(dashboardDefinition, flattenedData, query, dashboardFeatureFlags, partialDate);
    // Update the store
    if (requestedReportService) {
        requestData = await updateStore(services, tableId, dprUser.id, sections, req, filters.filters);
    }
    return {
        dashboardData: {
            token,
            id,
            reportId,
            name: dashboardDefinition.name,
            description: dashboardDefinition.description,
            reportName: reportDefinition.name,
            csrfToken,
            sections,
            filters,
            type: ReportType.DASHBOARD,
            actions: setDashboardActions(dashboardDefinition, reportDefinition, requestData),
            bookmarkConfig,
        },
    };
};
var DashboardUtils = {
    renderAsyncDashboard,
    getDefinitionData,
    setDashboardActions,
};

export { DashboardUtils as default, renderAsyncDashboard };
//# sourceMappingURL=utils.js.map
