'use strict';

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

var UserReports = require('../../../types/UserReports.js');
var localsHelper = require('../../../utils/localsHelper.js');
var ReportQuery = require('../../../types/ReportQuery.js');
var logger = require('../../../utils/logger.js');
var sessionHelper = require('../../../utils/sessionHelper.js');

const streamDownloadAsyncData = async (args) => {
    const { token, services, tableId, reportId, id, queryParams, res } = args;
    const query = {
        ...queryParams,
    };
    return services.reportingService.downloadAsyncReport(token, reportId, id, tableId, query, res);
};
const streamDownloadSyncData = async (args) => {
    const { token, services, queryParams, definition, res } = args;
    const { variant } = definition;
    const { resourceName, specification } = variant;
    if (!specification) {
        logger.default.error(`No specification found for definition ID: ${definition.id} variant ID: ${variant.id}`);
        throw new Error(`No specification found for definition ID: ${definition.id} variant ID: ${variant.id}`);
    }
    const reportQuery = new ReportQuery.ReportQuery({
        fields: specification.fields,
        template: specification.template,
        queryParams: {
            ...queryParams,
        },
        definitionsPath: queryParams.dataProductDefinitionsPath,
    });
    return services.reportingService.downloadSyncReport(token, resourceName, reportQuery, res);
};
const downloadReport = async ({ req, services, res, redirect, loadType, }) => {
    const { dprUser, token } = localsHelper.default.getValues(res);
    const { reportId, id, tableId, dataProductDefinitionsPath, cols: columns, sortedAsc, sortColumn } = req.body;
    const { downloadPermissionService } = services;
    const canDownloadReport = await downloadPermissionService.downloadEnabledForReport(dprUser.id, reportId, id);
    if (!canDownloadReport) {
        res.redirect(redirect);
    }
    else {
        const streamDownloadQueryParams = {
            dataProductDefinitionsPath,
            ...(columns && { columns: JSON.parse(columns) }),
            ...(sortedAsc && { sortedAsc }),
            ...(sortColumn && { sortColumn }),
        };
        const definition = await services.reportingService.getDefinition(token, reportId, id, dataProductDefinitionsPath);
        logger.default.info(`Initiating streaming...`);
        if (loadType === UserReports.LoadType.SYNC) {
            await streamDownloadSyncData({
                definition,
                services,
                token,
                queryParams: streamDownloadQueryParams,
                res,
            });
        }
        else {
            await streamDownloadAsyncData({
                services,
                token,
                reportId,
                id,
                tableId,
                queryParams: streamDownloadQueryParams,
                res,
            });
        }
    }
};
const setUpDownload = (res, req, definitionData, columns, loadType, requestData) => {
    const { downloadingEnabled } = localsHelper.default.getValues(res);
    let downloadConfig;
    if (downloadingEnabled) {
        const { definitionsPath, csrfToken } = localsHelper.default.getValues(res);
        const { downloadActionEndpoint } = localsHelper.default.getRouteLocals(res);
        const { tableId, id, reportId } = req.params;
        const downloadEnabled = sessionHelper.getActiveJourneyValue(req, { id, reportId }, 'downloadEnabled');
        const { reportName, name, specification } = definitionData;
        const sections = specification.sections || [];
        const downloadColumns = [...new Set([...columns.value, ...sections])];
        const sortColumn = requestData?.queryData?.['sortColumn'];
        const sortedAsc = requestData?.queryData?.['sortedAsc'];
        return {
            enabled: downloadingEnabled,
            name,
            reportName,
            reportId,
            id,
            tableId,
            columns: downloadColumns,
            definitionPath: definitionsPath,
            loadType,
            formAction: downloadActionEndpoint,
            canDownload: downloadEnabled,
            ...(sortColumn && { sortColumn }),
            ...(sortedAsc && { sortedAsc }),
            csrfToken,
        };
    }
    return downloadConfig;
};
var DownloadUtils = {
    downloadReport,
    setUpDownload,
};

exports.default = DownloadUtils;
exports.downloadReport = downloadReport;
exports.setUpDownload = setUpDownload;
//# sourceMappingURL=utils.js.map
