// (C) 2024-2026 GoodData Corporation
import { call, select } from "redux-saga/effects";
import { ensureAllTimeFilterForExport } from "../../../_staging/exportUtils/filterUtils.js";
import { invalidArgumentsProvided } from "../../events/general.js";
import { insightWidgetExportResolved, } from "../../events/insight.js";
import { selectExportResultPollingTimeout } from "../../store/config/configSelectors.js";
import { selectDashboardRef } from "../../store/meta/metaSelectors.js";
import { selectFilterContextFilters, selectFiltersByTab, } from "../../store/tabs/filterContext/filterContextSelectors.js";
export function* exportSlidesInsightWidgetHandler(ctx, cmd) {
    const { ref, filename, exportType, templateId } = cmd.payload;
    const { workspace, backend } = ctx;
    const dashboardRef = yield select(selectDashboardRef);
    if (!dashboardRef) {
        throw invalidArgumentsProvided(ctx, cmd, "Dashboard to export to slides must have an ObjRef.");
    }
    const filterContextFilters = yield select(selectFilterContextFilters);
    const effectiveFilters = ensureAllTimeFilterForExport(filterContextFilters);
    const filtersByTab = yield select(selectFiltersByTab);
    const effectiveFiltersByTab = Object.entries(filtersByTab).reduce((acc, [tabId, filters]) => {
        acc[tabId] = ensureAllTimeFilterForExport(filters);
        return acc;
    }, {});
    const timeout = yield select(selectExportResultPollingTimeout);
    const exportDashboardToPresentation = backend
        .workspace(workspace)
        .dashboards().exportDashboardToPresentation;
    const result = yield call(exportDashboardToPresentation, dashboardRef, exportType === "pptx" ? "PPTX" : "PDF", effectiveFilters, effectiveFiltersByTab, {
        widgetIds: [ref],
        filename,
        timeout,
        templateId,
    });
    // prepend hostname if provided so that the results are downloaded from there, not from where the app is hosted
    const fullUri = ctx.backend.config.hostname
        ? new URL(result.uri, ctx.backend.config.hostname).href
        : result.uri;
    const sanitizedResult = {
        ...result,
        uri: fullUri,
    };
    return insightWidgetExportResolved(ctx, sanitizedResult, cmd.correlationId);
}
//# sourceMappingURL=exportSlidesInsightWidgetHandler.js.map