import parseUrl from 'parseurl';
import { LoadType, ReportType, RequestStatus } from '../../../../../types/UserReports.js';
import { ReportQuery } from '../../../../../types/ReportQuery.js';
import PaginationUtils from '../../../../../components/_reports/report-page/report-template/report-pagination/utils.js';
import TotalsUtils from '../../../../../components/_reports/report-page/report-template/report-totals/utils.js';
import ColumnsUtils from '../../../../../components/_reports/report-heading/report-columns/report-columns-form/utils.js';
import ReportActionsUtils from '../../../../../components/_reports/report-heading/report-actions/utils.js';
import FiltersUtils from '../../../../../components/_filters/utils.js';
import SelectedFiltersUtils from '../../../../../components/_filters/filters-selected/utils.js';
import localsHelper from '../../../../../utils/localsHelper.js';
import { UserStoreItemBuilder } from '../../../../../utils/UserStoreItemBuilder.js';
import { FiltersType } from '../../../../../components/_filters/filtersTypeEnum.js';
import ReportTemplateUtils from '../../../../../components/_reports/report-page/report-template/utils.js';
import { setUpBookmark } from '../../../../../components/bookmark/utils.js';
import { setUpDownload } from '../../../download-report/utils.js';
import AsyncReportUtils from '../../async/report/utils.js';
import { getActiveJourneyValue } from '../../../../../utils/sessionHelper.js';

const setAsRecentlyViewed = async ({ req, services, reportName, name, description, reportId, id, userId, filters, }) => {
    const stateData = {
        type: ReportType.REPORT,
        reportId,
        id,
        reportName,
        description,
        name,
    };
    const interactiveQueryData = {
        query: req.query,
        querySummary: SelectedFiltersUtils.getQuerySummary(req.query, filters),
    };
    const recentlyViewedData = new UserStoreItemBuilder(stateData)
        .addInteractiveQuery(interactiveQueryData)
        .addStatus(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({
        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.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 = ColumnsUtils.getColumns(specification, req);
    // Get the count
    const count = await services.reportingService.getCount(reportDefinition.variant.resourceName, token, reportQuery);
    // Get the report actions
    const extractedDefinitionData = AsyncReportUtils.extractDataFromDefinition(reportDefinition);
    const bookmarkConfig = setUpBookmark(res, req, services.bookmarkService);
    const downloadConfig = setUpDownload(res, req, extractedDefinitionData, columns, LoadType.SYNC);
    const actions = ReportActionsUtils.setActions(extractedDefinitionData, downloadConfig);
    const feedbackFormHref = 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: 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 = ReportTemplateUtils.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 = PaginationUtils.getPaginationData(url, count, req);
        totals = TotalsUtils.getTotals(pagination.pageSize, pagination.currentPage, pagination.totalRows, dataTable.rowCount);
    }
    const filterData = await FiltersUtils.getFilters({
        fields: specification.fields,
        req,
        res,
        services,
        filtersType: filtersType || 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: ReportType.REPORT,
        classification,
        printable,
        warnings: reportData.warnings,
    };
};
var SyncReportUtils = {
    getRenderData,
    getReport,
    getReportData,
    getReportRenderData,
};

export { SyncReportUtils as default, getRenderData, getReport, getReportData, getReportRenderData };
//# sourceMappingURL=utils.js.map
