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