'use strict';

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

var dayjs = require('dayjs');
var UserReports = require('../../types/UserReports.js');
var requestStatusHelper = require('../../utils/requestStatusHelper.js');
var utils = require('../_filters/filters-selected/utils.js');
var reportListsHelper = require('../../utils/reportListsHelper.js');
var utils$3 = require('./requested/utils.js');
var utils$2 = require('./viewed/utils.js');
var utils$1 = require('./bookmarks/utils.js');
var localsHelper = require('../../utils/localsHelper.js');
var DateMapper = require('../../utils/DateMapper/DateMapper.js');
var UserStoreItemBuilder = require('../../utils/UserStoreItemBuilder.js');
var queryMappers = require('../../utils/queryMappers.js');

const formatData = (reportData) => {
    const reportDataCopy = JSON.parse(JSON.stringify(reportData));
    const { executionId, tableId, variantName, name, reportId, variantId, id, description, query, interactiveQuery, status, reportName, dataProductDefinitionsPath, type: reportType, url, } = reportDataCopy;
    let summary = [];
    if (query) {
        summary = query.summary;
    }
    let interactiveSummary = [];
    if (interactiveQuery) {
        interactiveSummary = interactiveQuery.summary;
    }
    const type = reportType || UserReports.ReportType.REPORT;
    return {
        id: executionId,
        text: name || variantName || '',
        reportName,
        description,
        tag: 'MIS',
        summary,
        interactiveSummary,
        status,
        type,
        ...(status && setDataFromStatus(status, reportDataCopy)),
        meta: {
            reportId,
            id: variantId || id,
            executionId,
            tableId,
            status,
            type,
            dataProductDefinitionsPath,
            pollingUrl: url?.polling?.pathname,
            reportUrl: url?.report?.pathname,
        },
    };
};
const formatTable = (data, type) => {
    const rows = data.map((card) => {
        return formatTableRow(card, type);
    });
    return {
        rows,
        head: [
            { text: 'Product', classes: 'dpr-req-product-head' },
            { text: 'Filters', classes: 'dpr-req-filters-head' },
            { text: 'Status', classes: 'dpr-req-status-head' },
            { text: 'Actions', classes: 'dpr-req-actions-head' },
        ],
    };
};
const formatTableRow = (data, type) => {
    let statusClass;
    let itemActions = '';
    const { href, id, reportName, text, timestamp, type: reportType, status } = data;
    if (href) {
        switch (status) {
            case UserReports.RequestStatus.FAILED:
                statusClass = 'govuk-tag--red';
                itemActions = id ? reportListsHelper.itemActionsHtml(href, id, type, status) : '';
                break;
            case UserReports.RequestStatus.EXPIRED:
                statusClass = 'govuk-tag--grey';
                itemActions = id ? reportListsHelper.itemActionsHtml(href, id, type, status) : '';
                break;
            case UserReports.RequestStatus.ABORTED:
                statusClass = 'govuk-tag--orange';
                itemActions = id ? reportListsHelper.itemActionsHtml(href, id, type, status) : '';
                break;
            case UserReports.RequestStatus.READY:
            case UserReports.RequestStatus.FINISHED:
                itemActions = `<a class=govuk-link govuk-link--no-visited-state dpr-type__${reportType}' href="${href}">Go to ${reportType}</a>`;
                statusClass = 'govuk-tag--green';
                break;
            case UserReports.RequestStatus.PICKED:
            case UserReports.RequestStatus.SUBMITTED:
            case UserReports.RequestStatus.STARTED:
                itemActions = `<a class='govuk-link govuk-link--no-visited-state dpr-type__${reportType}' href="${href}">Go to status</a>`;
                break;
        }
    }
    let filtersSummary = '';
    if (data.summary || data.interactiveSummary) {
        filtersSummary = createSummaryHtml(data);
    }
    return [
        {
            html: reportListsHelper.createListItemProduct(reportName, text, reportType, timestamp),
        },
        { html: filtersSummary },
        {
            html: `<strong class="govuk-tag dpr-request-status-tag ${statusClass}">${status}</strong>`,
            classes: 'dpr-req-cell dpr-req-cell__status',
        },
        {
            html: `${itemActions}`,
            classes: 'dpr-req-cell dpr-req-cell__status',
        },
    ];
};
const getTotals = (formattedCount, maxRows = 20) => {
    return {
        amount: formattedCount,
        shown: maxRows && formattedCount > maxRows ? maxRows : formattedCount,
        max: maxRows,
    };
};
const createSummaryHtml = (data) => {
    const summaryHtml = data.summary
        ?.map((item) => `<li class="govuk-body-s dpr-query-summary"><strong>${item.name}</strong>: ${item.value}</li>`)
        .join('');
    const interactiveSummaryHtml = data.interactiveSummary
        ?.map((item) => `<li class="govuk-body-s dpr-interactive-query-summary"><strong>${item.name}</strong>: ${item.value}</li>`)
        .join('');
    return `<ul class="dpr-card-group__item__filters-list govuk-!-margin-top-0 govuk-!-margin-bottom-0">${summaryHtml}${interactiveSummaryHtml}</ul>`;
};
const getMeta = (formattedData, endpoint) => {
    return formattedData.map((d) => {
        return {
            reportId: d.meta?.reportId,
            id: d.meta.id,
            executionId: d.meta.executionId,
            tableId: d.meta.tableId,
            status: d.meta.status,
            requestedAt: d.meta.requestedAt,
            type: d.meta.type,
            dataProductDefinitionsPath: d.meta.dataProductDefinitionsPath,
            pollingUrl: d.meta.pollingUrl,
            reportUrl: d.meta.reportUrl,
            endpoint,
        };
    });
};
const setDataFromStatus = (status, reportsData) => {
    let timestamp;
    let href;
    let formattedDate;
    const { url, timestamp: time } = reportsData;
    const polling = url?.polling;
    const request = url?.request;
    const report = url?.report;
    const dateMapper = new DateMapper.DateMapper();
    switch (status) {
        case UserReports.RequestStatus.FAILED: {
            formattedDate = time.failed
                ? dateMapper.toDateString(time.failed, 'local-date')
                : dayjs().format('DD/MM/YYYY');
            href = polling?.fullUrl;
            timestamp = `Failed at: ${formattedDate}`;
            break;
        }
        case UserReports.RequestStatus.ABORTED: {
            href = request?.fullUrl;
            formattedDate = dateMapper.toDateString(time.aborted, 'local-date');
            timestamp = `Aborted at: ${formattedDate}`;
            break;
        }
        case UserReports.RequestStatus.FINISHED:
            href = report?.fullUrl;
            formattedDate = dateMapper.toDateString(time.completed, 'local-date');
            timestamp = `Ready at: ${formattedDate}`;
            break;
        case UserReports.RequestStatus.EXPIRED: {
            href = request?.fullUrl;
            formattedDate = dateMapper.toDateString(time.expired, 'local-date');
            timestamp = `Expired at: ${formattedDate}`;
            break;
        }
        case UserReports.RequestStatus.READY: {
            href = report?.fullUrl;
            formattedDate = dateMapper.toDateString(time.lastViewed, 'local-date');
            timestamp = `Last viewed: ${formattedDate}`;
            break;
        }
        case UserReports.RequestStatus.SUBMITTED:
        case UserReports.RequestStatus.STARTED:
        case UserReports.RequestStatus.PICKED:
            href = polling?.fullUrl;
            formattedDate = dateMapper.toDateString(time.requested, 'local-date');
            timestamp = `Requested at: ${formattedDate}`;
            break;
        default:
            formattedDate = dateMapper.toDateString(time.lastViewed, 'local-date');
            timestamp = `Last viewed: ${formattedDate}`;
            break;
    }
    return {
        timestamp,
        href,
    };
};
const renderList = async ({ res, reportsData, maxRows, filterFunction, type, }) => {
    const { csrfToken } = localsHelper.default.getValues(res);
    let formatted = reportsData.filter(filterFunction).map(formatData);
    const formattedCount = formatted.length;
    if (maxRows)
        formatted = formatted.slice(0, maxRows);
    const tableData = formatTable(formatted, type);
    const { requestedListPath, recentlyViewedListPath } = localsHelper.default.getRouteLocals(res);
    const endpoint = type === 'requested' ? requestedListPath : recentlyViewedListPath;
    const head = {
        ...(formatted.length && { href: endpoint }),
        ...(!formatted.length && { emptyMessage: `You have 0 ${type} reports` }),
    };
    const result = {
        head,
        tableData,
        total: getTotals(formattedCount, maxRows),
        meta: getMeta(formatted, endpoint),
        csrfToken,
        ...(maxRows && { maxRows }),
    };
    return result;
};
const updateExpiredStatus = async ({ req, res, services }) => {
    const { dprUser } = localsHelper.default.getValues(res);
    const report = await requestStatusHelper.getExpiredStatus({ req, res, services });
    if (report && report.isExpired) {
        await services.recentlyViewedService.setToExpired(report.executionId, dprUser.id);
        await services.requestedReportService.setToExpired(report.executionId, dprUser.id);
    }
    return report ? report.isExpired : false;
};
const initUserReports = async ({ services, res, maxRows = 6, }) => {
    const { requestedReports, recentlyViewedReports, bookmarkingEnabled } = localsHelper.default.getValues(res);
    const requestedReportsList = await renderList({
        res,
        reportsData: requestedReports,
        filterFunction: utils$3.default.filterReports,
        maxRows,
        type: 'requested',
    });
    const viewedReportsList = await renderList({
        res,
        reportsData: recentlyViewedReports,
        filterFunction: utils$2.default.filterReports,
        maxRows,
        type: 'viewed',
    });
    let bookmarks;
    if (bookmarkingEnabled) {
        bookmarks = await utils$1.default.renderBookmarkList({
            res,
            services,
            maxRows,
        });
    }
    return {
        requestedReports: requestedReportsList,
        viewedReports: viewedReportsList,
        bookmarks,
    };
};
const updateLastViewed = async ({ req, services, reportStateData, userId, filters, }) => {
    const { type, reportId, reportName, description, id, name, executionId, tableId, query, url } = reportStateData;
    const reportData = { type, reportId, reportName, description, id, name };
    const executionData = { executionId, tableId };
    const queryData = query ? { query: query.data, querySummary: query.summary } : { query: {}, querySummary: [] };
    const filtersQuery = queryMappers.extractFiltersFromQuery(req.query);
    const columns = req.query?.['columns'];
    const { selectedPage, pageSize, sortColumn, sortedAsc } = req.query;
    const reqQuery = {
        ...filtersQuery,
        ...(columns && { columns }),
        ...(selectedPage && { selectedPage }),
        ...(pageSize && { pageSize }),
        ...(sortColumn && { sortColumn }),
        ...(sortedAsc && { sortedAsc }),
    };
    const interactiveQueryData = {
        query: reqQuery,
        querySummary: utils.default.getQuerySummary(filtersQuery, filters),
    };
    const recentlyViewedData = new UserStoreItemBuilder.UserStoreItemBuilder(reportData)
        .addExecutionData(executionData)
        .addQuery(queryData)
        .addInteractiveQuery(interactiveQueryData)
        .addStatus(UserReports.RequestStatus.READY)
        .addTimestamp()
        .addAsyncUrls(url)
        .addReportUrls(req)
        .build();
    if (executionId)
        await services.requestedReportService.updateLastViewed(executionId, userId);
    await services.recentlyViewedService.setRecentlyViewed(recentlyViewedData, userId);
};
var UserReportsListUtils = {
    renderList,
    updateExpiredStatus,
    initUserReports,
    updateLastViewed,
};

exports.default = UserReportsListUtils;
exports.initUserReports = initUserReports;
exports.renderList = renderList;
exports.setDataFromStatus = setDataFromStatus;
exports.updateExpiredStatus = updateExpiredStatus;
exports.updateLastViewed = updateLastViewed;
//# sourceMappingURL=utils.js.map
