'use strict';

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

var parseUrl = require('parseurl');
var UserReports = require('../../../../../types/UserReports.js');
var ReportQuery = require('../../../../../types/ReportQuery.js');
var utils$6 = require('../../../../../components/_reports/report-page/report-template/report-pagination/utils.js');
var utils$7 = require('../../../../../components/_reports/report-page/report-template/report-totals/utils.js');
var utils = require('../../../../../components/_reports/report-heading/report-columns/report-columns-form/utils.js');
var utils$4 = require('../../../../../components/_reports/report-heading/report-actions/utils.js');
var utils$8 = require('../../../../../components/_filters/utils.js');
var utils$9 = require('../../../../../components/_filters/filters-selected/utils.js');
var localsHelper = require('../../../../../utils/localsHelper.js');
var UserStoreItemBuilder = require('../../../../../utils/UserStoreItemBuilder.js');
var filtersTypeEnum = require('../../../../../components/_filters/filtersTypeEnum.js');
var utils$5 = require('../../../../../components/_reports/report-page/report-template/utils.js');
var utils$2 = require('../../../../../components/bookmark/utils.js');
var utils$3 = require('../../../download-report/utils.js');
var utils$1 = require('../../async/report/utils.js');
var sessionHelper = require('../../../../../utils/sessionHelper.js');

const setAsRecentlyViewed = async ({ req, services, reportName, name, description, reportId, id, userId, filters, }) => {
    const stateData = {
        type: UserReports.ReportType.REPORT,
        reportId,
        id,
        reportName,
        description,
        name,
    };
    const interactiveQueryData = {
        query: req.query,
        querySummary: utils$9.default.getQuerySummary(req.query, filters),
    };
    const recentlyViewedData = new UserStoreItemBuilder.UserStoreItemBuilder(stateData)
        .addInteractiveQuery(interactiveQueryData)
        .addStatus(UserReports.RequestStatus.READY)
        .addTimestamp()
        .addReportUrls(req)
        .build();
    await services.recentlyViewedService?.setRecentlyViewed(recentlyViewedData, userId);
};
const getReportData = async ({ services, req, token, reportId, id, dataProductDefinitionsPath, }) => {
    const reportDefinition = await services.reportingService.getDefinition(token, reportId, id, dataProductDefinitionsPath);
    const { variant } = reportDefinition;
    const { resourceName, specification } = variant;
    const reportQuery = new ReportQuery.ReportQuery({
        fields: specification?.fields || [],
        template: specification?.template || 'list',
        queryParams: req.query,
        definitionsPath: dataProductDefinitionsPath,
    });
    return {
        reportData: await services.reportingService.getListWithWarnings(resourceName, token, reportQuery),
        reportDefinition,
        reportQuery,
    };
};
const getReport = async ({ req, res, services }) => {
    const { token, csrfToken, dprUser } = localsHelper.default.getValues(res);
    const { reportId, id } = req.params;
    const dataProductDefinitionsPath = req.query['dataProductDefinitionsPath'];
    // Get the report data
    const { reportData, reportDefinition, reportQuery } = await getReportData({
        services,
        req,
        token,
        reportId,
        id,
        dataProductDefinitionsPath,
    });
    const { variant } = reportDefinition;
    const { specification } = variant;
    if (!specification) {
        throw new Error('No specification found in variant definition');
    }
    // Get the columns
    const columns = utils.default.getColumns(specification, req);
    // Get the count
    const count = await services.reportingService.getCount(reportDefinition.variant.resourceName, token, reportQuery);
    // Get the report actions
    const extractedDefinitionData = utils$1.default.extractDataFromDefinition(reportDefinition);
    const bookmarkConfig = utils$2.setUpBookmark(res, req, services.bookmarkService);
    const downloadConfig = utils$3.setUpDownload(res, req, extractedDefinitionData, columns, UserReports.LoadType.SYNC);
    const actions = utils$4.default.setActions(extractedDefinitionData, downloadConfig);
    const feedbackFormHref = sessionHelper.getActiveJourneyValue(req, { id, reportId }, 'feedbackSubmissionFormPath');
    // Get the table data and filters, pagination etc
    const renderData = await getRenderData({
        req,
        res,
        services,
        reportDefinition,
        reportQuery,
        reportData,
        count,
        columns,
    });
    if (Object.keys(renderData).length) {
        await setAsRecentlyViewed({
            req,
            services,
            reportName: renderData.reportName,
            name: renderData.name,
            description: renderData.description || '',
            reportId,
            id,
            userId: dprUser.id,
            filters: renderData.filterData.filters,
        });
    }
    return {
        renderData: {
            feedbackFormHref,
            ...renderData,
            csrfToken,
            loadType: UserReports.LoadType.SYNC,
            reportId,
            id,
            bookmarkConfig,
            downloadConfig,
            actions,
            dataProductDefinitionsPath,
        },
    };
};
const getReportRenderData = async ({ req, res, services, count, specification, reportQuery, data, filtersType, definition, columns, }) => {
    const url = parseUrl(req);
    const fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
    const pathname = url?.search ? req.originalUrl.split(url.search)[0] : req.originalUrl;
    const reportDefinition = {
        ...definition,
        variant: {
            ...definition.variant,
            interactive: true,
        },
    };
    // Get the data table
    const dataTable = utils$5.default.createReportTemplateData(reportDefinition, columns, data, [], // child data - N/A for sync reports
    [], // summaries data - N/A for sync reports
    reportQuery);
    let pagination;
    let totals;
    if (url) {
        pagination = utils$6.default.getPaginationData(url, count, req);
        totals = utils$7.default.getTotals(pagination.pageSize, pagination.currentPage, pagination.totalRows, dataTable.rowCount);
    }
    const filterData = await utils$8.default.getFilters({
        fields: specification.fields,
        req,
        res,
        services,
        filtersType: filtersType || filtersTypeEnum.FiltersType.INTERACTIVE,
    });
    return {
        dataTable,
        totals,
        filterData,
        columns,
        pagination,
        reportUrl: pathname.replace('/download-disabled', '').replace('/download-disabled?', ''),
        reportSearch: url?.search,
        encodedSearch: url?.search ? encodeURIComponent(url.search) : undefined,
        fullUrl,
        template: specification.template,
    };
};
const getRenderData = async ({ req, res, services, reportDefinition, reportQuery, reportData, count, columns, }) => {
    const { name: reportName, description: reportDescription } = reportDefinition;
    const { specification, name, description, classification, printable } = reportDefinition.variant;
    const { data } = reportData;
    if (!specification) {
        throw new Error('No specicication found in definition');
    }
    const reportRenderData = await getReportRenderData({
        req,
        res,
        services,
        count,
        specification,
        reportQuery,
        data,
        definition: reportDefinition,
        columns,
    });
    return {
        ...reportRenderData,
        reportName,
        name,
        description: description || reportDescription,
        count,
        type: UserReports.ReportType.REPORT,
        classification,
        printable,
        warnings: reportData.warnings,
    };
};
var SyncReportUtils = {
    getRenderData,
    getReport,
    getReportData,
    getReportRenderData,
};

exports.default = SyncReportUtils;
exports.getRenderData = getRenderData;
exports.getReport = getReport;
exports.getReportData = getReportData;
exports.getReportRenderData = getReportRenderData;
//# sourceMappingURL=utils.js.map
