// (C) 2021-2026 GoodData Corporation
import { call, put, select } from "redux-saga/effects";
import { ensureAllTimeFilterForExport } from "../../../_staging/exportUtils/filterUtils.js";
import { dashboardExportToPdfPresentationRequested, dashboardExportToPdfPresentationResolved, } from "../../events/dashboard.js";
import { invalidArgumentsProvided } from "../../events/general.js";
import { selectExportResultPollingTimeout } from "../../store/config/configSelectors.js";
import { selectDashboardRef } from "../../store/meta/metaSelectors.js";
import { selectFilterContextFilters, selectFiltersByTab, } from "../../store/tabs/filterContext/filterContextSelectors.js";
function exportDashboardToPdfPresentation(ctx, dashboardRef, filters, filtersByTab, options) {
    const { backend, workspace } = ctx;
    return backend
        .workspace(workspace)
        .dashboards()
        .exportDashboardToPresentation(dashboardRef, "PDF", filters, filtersByTab, options);
}
export function* exportDashboardToPdfPresentationHandler(ctx, cmd) {
    yield put(dashboardExportToPdfPresentationRequested(ctx, cmd.correlationId));
    const dashboardRef = yield select(selectDashboardRef);
    if (!dashboardRef) {
        throw invalidArgumentsProvided(ctx, cmd, "Dashboard to export to PDF presentation must have an ObjRef.");
    }
    const filterContextFilters = yield select(selectFilterContextFilters);
    const filtersByTab = yield select(selectFiltersByTab);
    const effectiveFilters = ensureAllTimeFilterForExport(cmd.payload?.filters ?? filterContextFilters);
    const effectiveFiltersByTab = Object.entries(filtersByTab).reduce((acc, [tabId, filters]) => {
        acc[tabId] = ensureAllTimeFilterForExport(filters);
        return acc;
    }, {});
    const timeout = yield select(selectExportResultPollingTimeout);
    const options = {
        ...(cmd.payload?.options ?? {}),
        exportMetadata: cmd.payload?.exportMetadata,
        timeout,
    };
    const result = yield call(exportDashboardToPdfPresentation, ctx, dashboardRef, effectiveFilters, effectiveFiltersByTab, options);
    // 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 dashboardExportToPdfPresentationResolved(ctx, sanitizedResult, cmd.correlationId);
}
//# sourceMappingURL=exportDashboardToPdfPresentationHandler.js.map