'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var UserReports = require('../../../../../types/UserReports.js');
var definitionUtils = require('../../../../../utils/definitionUtils.js');
var utils$4 = require('../../../../../components/_filters/utils.js');
var utils$2 = require('../../../../../components/_reports/report-heading/report-actions/utils.js');
var ReportQuery = require('../../../../../types/ReportQuery.js');
var localsHelper = require('../../../../../utils/localsHelper.js');
var _enum = require('../../../../../components/_filters/filter-input/enum.js');
var utils$3 = require('../../../../../components/_dashboards/dashboard-visualisation/utils.js');
var utils$1 = require('../../../../../components/_dashboards/dashboard-section/utils.js');
var validate = require('./validate.js');
var utils = require('../../../../../components/bookmark/utils.js');
var utils$5 = require('../../../../../components/_filters/filters-applied/utils.js');
var queryMappers = require('../../../../../utils/queryMappers.js');
var utils$6 = require('../../utils.js');
var ErrorHandler = require('../../../../../utils/ErrorHandler/ErrorHandler.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 utils$2.default.getActions(actions);
};
const getDefinitionData = async ({ req, res, services, queryData, }) => {
    const { token } = localsHelper.default.getValues(res);
    const { reportId, id, tableId } = req.params;
    const dataProductDefinitionsPath = req.query['dataProductDefinitionsPath'];
    // Dashboard Definition,
    const dashboardDefinition = await services.dashboardService.getDefinition(token, reportId, id, dataProductDefinitionsPath, queryData);
    // Validate definition
    validate.DashboardSchema.parse(dashboardDefinition);
    // validate visualisations
    await utils$3.validateDashboardVisualisations(dashboardDefinition);
    // Report summary data
    const reportDefinition = await definitionUtils.default.getReportSummary(reportId, services.reportingService, token, dataProductDefinitionsPath);
    // Get the filters
    const fields = definitionUtils.getDashboardFields(dashboardDefinition);
    const filters = await utils$4.default.getInteractiveFilters({
        fields,
        req,
    });
    // Get the applied Filters
    const appliedFilters = utils$5.buildAppliedFilters(req, { reportId, id, tableId }, fields);
    // Create the query
    const query = new ReportQuery.ReportQuery({
        fields,
        queryParams: queryMappers.extractFiltersFromQuery(req.query),
        definitionsPath: dataProductDefinitionsPath,
        reportType: UserReports.ReportType.DASHBOARD,
    }).toRecordWithFilterPrefix(true);
    return {
        query,
        filters,
        dashboardDefinition,
        reportDefinition,
        appliedFilters,
        fields,
    };
};
const updateStore = async (services, tableId, userId, sections, req, fields) => {
    const { requestedReportService } = services;
    const dashboardRequestData = await requestedReportService.getReportByTableId(tableId, userId);
    // Add to recently viewed
    if (sections && sections.length && dashboardRequestData) {
        await utils$6.updateLastViewedAsync(req, services, dashboardRequestData, userId, fields);
    }
    return dashboardRequestData;
};
const getPartialDate = (filters) => {
    let partialDate;
    const granularDateRangeFilter = (filters.find((f) => f.type === _enum.FilterType.granularDateRange.toLowerCase()));
    if (granularDateRangeFilter) {
        partialDate = granularDateRangeFilter.value.partialDate;
    }
    return partialDate;
};
const renderAsyncDashboard = async ({ req, res, services }) => {
    const { token, csrfToken, dprUser } = localsHelper.default.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, appliedFilters, fields } = await getDefinitionData({
        req,
        res,
        services,
        queryData,
    });
    // Get the dashboard data and check if expired
    const { dashboardData, expired } = await getDashboardData(token, reportId, id, tableId, query, services);
    const partialDate = getPartialDate(filters);
    const bookmarkConfig = utils.setUpBookmark(res, req, bookmarkService);
    // Get the dashboard parts
    const dashboardFeatureFlags = res.app.locals['featureFlags'].flags;
    const sections = utils$1.createDashboardSections(dashboardDefinition, dashboardData, query, dashboardFeatureFlags, partialDate);
    // Update the store
    if (requestedReportService) {
        requestData = await updateStore(services, tableId, dprUser.id, sections, req, fields);
    }
    return {
        dashboardData: {
            token,
            id,
            reportId,
            name: dashboardDefinition.name,
            description: dashboardDefinition.description,
            reportName: reportDefinition.name,
            csrfToken,
            sections,
            filters,
            type: UserReports.ReportType.DASHBOARD,
            actions: setDashboardActions(dashboardDefinition, reportDefinition, requestData),
            bookmarkConfig,
            appliedFilters,
        },
        expired,
    };
};
/**
 * Gets the data for a dashboard
 *
 * @param {string} token
 * @param {string} reportId
 * @param {string} id
 * @param {string} tableId
 * @param {(Record<string, string | string[]>)} query
 * @param {Services} services
 * @return {*}
 */
const getDashboardData = async (token, reportId, id, tableId, query, services) => {
    let dashboardData = [];
    let expired = false;
    try {
        const dashboardResultData = await services.dashboardService.getAsyncDashboard(token, id, reportId, tableId, query);
        dashboardData = Array.isArray(dashboardResultData) ? dashboardResultData.flat().filter(Boolean) : [];
    }
    catch (error) {
        const dprError = new ErrorHandler.ErrorHandler(error).formatError();
        if (dprError.status === 404) {
            expired = true;
        }
        else {
            throw error;
        }
    }
    return {
        dashboardData,
        expired,
    };
};
var DashboardUtils = {
    renderAsyncDashboard,
    getDefinitionData,
    setDashboardActions,
};

exports.default = DashboardUtils;
exports.renderAsyncDashboard = renderAsyncDashboard;
//# sourceMappingURL=utils.js.map
