// (C) 2021-2026 GoodData Corporation
import { call, put, select } from "redux-saga/effects";
import { dashboardExportToExcelRequested, dashboardExportToExcelResolved, } from "../../events/dashboard.js";
import { invalidArgumentsProvided } from "../../events/general.js";
import { selectExportResultPollingTimeout } from "../../store/config/configSelectors.js";
import { selectFilterViews } from "../../store/filterViews/filterViewsReducersSelectors.js";
import { selectDashboardRef, selectIsFiltersChanged } from "../../store/meta/metaSelectors.js";
import { selectFilterContextFilters, selectFiltersByTab, } from "../../store/tabs/filterContext/filterContextSelectors.js";
function exportDashboardToTabular(ctx, dashboardRef, title, mergeHeaders, exportInfo, widgetIds, dashboardFiltersOverride, filtersByTab, format, pdfConfiguration, timeout) {
    const { backend, workspace } = ctx;
    return backend.workspace(workspace).dashboards().exportDashboardToTabular(dashboardRef, {
        title,
        format,
        mergeHeaders,
        exportInfo,
        dashboardFiltersOverride,
        dashboardTabsFiltersOverrides: filtersByTab,
        widgetIds,
        pdfConfiguration,
        timeout,
    });
}
export function* exportToTabularHandler(ctx, cmd) {
    yield put(dashboardExportToExcelRequested(ctx, cmd.correlationId));
    const dashboardRef = yield select(selectDashboardRef);
    if (!dashboardRef) {
        throw invalidArgumentsProvided(ctx, cmd, "Dashboard to export to tabular format must have an ObjRef.");
    }
    const { mergeHeaders, exportInfo, widgetIds, fileName, format, pdfConfiguration } = cmd.payload;
    const isFilterContextChanged = yield select(selectIsFiltersChanged);
    const filterViews = yield select(selectFilterViews);
    const hasDefaultFilterViewApplied = filterViews.some((filterView) => filterView.isDefault);
    const filterContextFilters = yield select(selectFilterContextFilters);
    const filtersByTab = yield select(selectFiltersByTab);
    const timeout = yield select(selectExportResultPollingTimeout);
    const result = yield call(exportDashboardToTabular, ctx, dashboardRef, fileName, mergeHeaders, exportInfo, widgetIds, isFilterContextChanged || hasDefaultFilterViewApplied ? filterContextFilters : undefined, isFilterContextChanged || hasDefaultFilterViewApplied ? filtersByTab : undefined, format, pdfConfiguration, timeout);
    // 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 dashboardExportToExcelResolved(ctx, sanitizedResult, cmd.correlationId);
}
//# sourceMappingURL=exportToTabularHandler.js.map