import { captureException } from '@sentry/node';
import { ReportType, LoadType } from '../../../types/UserReports.js';
import ShowMoreUtils from '../../show-more/utils.js';
import logger from '../../../utils/logger.js';
import DefinitionUtils from '../../../utils/definitionUtils.js';
import { setInitialHref, createListItemProduct, createListActions } from '../../../utils/reportListsHelper.js';
import localsHelper from '../../../utils/localsHelper.js';

const formatBookmarks = async (bookmarksData) => {
    return bookmarksData
        .map((report) => {
        return formatBookmark(report);
    })
        .sort((a, b) => a.text.localeCompare(b.text));
};
const formatBookmark = (bookmarkData) => {
    const reportData = JSON.parse(JSON.stringify(bookmarkData));
    const { id, name, description, href, reportName, type } = reportData;
    return {
        id,
        reportName,
        text: name,
        description,
        href,
        type: type,
    };
};
const formatTable = async (bookmarksData, bookmarkService, csrfToken, userId, endpoint, maxRows) => {
    const userConfig = await bookmarkService.getState(userId);
    const rows = await Promise.all(bookmarksData
        .sort((a, b) => a.name.localeCompare(b.name))
        .map(async (bookmark) => {
        return formatTableData(bookmark, bookmarkService, csrfToken, userConfig, endpoint);
    }));
    return {
        rows: maxRows ? rows.slice(0, maxRows) : rows,
        head: [
            { text: 'Product', classes: 'dpr-req-product-head' },
            { text: 'Description', classes: 'dpr-bm-description-head' },
            { text: 'Actions', classes: 'dpr-bm-actions-head' },
        ],
    };
};
const formatTableData = async (bookmarksData, bookmarkService, csrfToken, userConfig, endpoint) => {
    const { description, reportName, reportId, id, href, name, type, loadType } = bookmarksData;
    const bookmarkHtml = await bookmarkService.createBookMarkButtonHtml({
        userConfig,
        reportId,
        id,
        csrfToken,
        ctxId: 'bookmark-list',
        reportType: type,
        // We don't have the data here, and missing reports should never get into bookmarked, viewed or requested
        isMissing: false,
        endpoint,
    });
    return [
        {
            html: createListItemProduct(reportName, name, type),
        },
        { html: ShowMoreUtils.createShowMoreHtml(description), classes: 'dpr-req-cell' },
        {
            html: createListActions(href, type, loadType, bookmarkHtml),
            classes: 'dpr-req-cell dpr-req-cell__status',
        },
    ];
};
const mapBookmarkIdsToDefinition = async (bookmarks, res, token, services) => {
    const bookmarkData = [];
    const { definitionsPath } = localsHelper.getValues(res);
    await Promise.all(bookmarks.map(async (bookmark) => {
        let definition;
        const { reportId, id, automatic, type } = bookmark;
        const reportType = type ? type : ReportType.REPORT;
        try {
            let name = '';
            let description = '';
            let loadType = LoadType.ASYNC;
            const href = setInitialHref(loadType, reportType, reportId, id, res);
            const procuctSummary = await DefinitionUtils.getReportSummary(reportId, services.reportingService, token, definitionsPath);
            const reportName = procuctSummary.name;
            if (reportType === ReportType.REPORT) {
                const variantSummary = procuctSummary.variants.find((v) => v.id === id);
                definition = await services.reportingService.getDefinition(token, reportId, id, definitionsPath);
                name = definition.variant.name;
                description = definition.variant.description || definition.description || '';
                loadType = variantSummary?.loadType || loadType;
            }
            if (reportType === ReportType.DASHBOARD) {
                definition = await services.dashboardService.getDefinition(token, reportId, id, definitionsPath);
                name = definition.name;
                description = definition.description || '';
            }
            if (definition) {
                bookmarkData.push({
                    reportId,
                    id,
                    reportName,
                    name,
                    description,
                    type: reportType,
                    href,
                    loadType,
                    automatic,
                });
            }
        }
        catch (error) {
            captureException(error);
            // DPD has been deleted so API throws error
            logger.warn(`Failed to map bookmark for: Report ${reportId}, variant ${id}`);
            const { dprUser } = localsHelper.getValues(res);
            await services.bookmarkService.removeBookmark(dprUser.id, id, reportId);
        }
    }));
    return bookmarkData;
};
const renderBookmarkList = async ({ services, maxRows = 20, res, }) => {
    const { token, csrfToken, dprUser, bookmarks } = localsHelper.getValues(res);
    const { bookmarkActionEndpoint, bookmarkListPath } = localsHelper.getRouteLocals(res);
    const bookmarksData = await mapBookmarkIdsToDefinition(bookmarks, res, token, services);
    let formatted = await formatBookmarks(bookmarksData);
    const formattedCount = formatted.length;
    if (maxRows)
        formatted = formatted.slice(0, maxRows);
    const tableData = await formatTable(bookmarksData, services.bookmarkService, csrfToken, dprUser.id, bookmarkActionEndpoint, maxRows);
    const head = {
        ...(formatted.length && { href: bookmarkListPath }),
        ...(!formatted.length && { emptyMessage: 'You have 0 bookmarked reports' }),
    };
    const total = {
        amount: formattedCount,
        shown: formattedCount > maxRows ? maxRows : formattedCount,
        max: maxRows,
    };
    const result = {
        head,
        tableData,
        total,
        csrfToken,
        type: 'bookmark',
    };
    return result;
};
var BookmarklistUtils = {
    renderBookmarkList,
};

export { BookmarklistUtils as default, formatBookmark, formatBookmarks, renderBookmarkList };
//# sourceMappingURL=utils.js.map
