define(["require", "exports", "tslib", "react", "@fluentui/react", "../DonutChart/index", "../VerticalStackedBarChart/index", "@fluentui/chart-utilities", "@fluentui/chart-utilities", "./PlotlySchemaAdapter", "../LineChart/index", "../HorizontalBarChartWithAxis/index", "../AreaChart/index", "../HeatMapChart/index", "../SankeyChart/SankeyChart", "../GaugeChart/index", "../GroupedVerticalBarChart/index", "../VerticalBarChart/index", "../ResponsiveContainer/withResponsiveContainer", "../ScatterChart/index", "../ChartTable/index", "../FunnelChart/FunnelChart", "../Legends/index"], function (require, exports, tslib_1, React, react_1, index_1, index_2, chart_utilities_1, chart_utilities_2, PlotlySchemaAdapter_1, index_3, index_4, index_5, index_6, SankeyChart_1, index_7, index_8, index_9, withResponsiveContainer_1, index_10, index_11, FunnelChart_1, index_12) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeclarativeChart = void 0;
    var ResponsiveDonutChart = (0, withResponsiveContainer_1.withResponsiveContainer)(index_1.DonutChart);
    var ResponsiveVerticalStackedBarChart = (0, withResponsiveContainer_1.withResponsiveContainer)(index_2.VerticalStackedBarChart);
    var ResponsiveLineChart = (0, withResponsiveContainer_1.withResponsiveContainer)(index_3.LineChart);
    var ResponsiveHorizontalBarChartWithAxis = (0, withResponsiveContainer_1.withResponsiveContainer)(index_4.HorizontalBarChartWithAxis);
    var ResponsiveAreaChart = (0, withResponsiveContainer_1.withResponsiveContainer)(index_5.AreaChart);
    var ResponsiveHeatMapChart = (0, withResponsiveContainer_1.withResponsiveContainer)(index_6.HeatMapChart);
    var ResponsiveSankeyChart = (0, withResponsiveContainer_1.withResponsiveContainer)(SankeyChart_1.SankeyChart);
    var ResponsiveGaugeChart = (0, withResponsiveContainer_1.withResponsiveContainer)(index_7.GaugeChart);
    var ResponsiveGroupedVerticalBarChart = (0, withResponsiveContainer_1.withResponsiveContainer)(index_8.GroupedVerticalBarChart);
    var ResponsiveVerticalBarChart = (0, withResponsiveContainer_1.withResponsiveContainer)(index_9.VerticalBarChart);
    var ResponsiveScatterChart = (0, withResponsiveContainer_1.withResponsiveContainer)(index_10.ScatterChart);
    var ResponsiveChartTable = (0, withResponsiveContainer_1.withResponsiveContainer)(index_11.ChartTable);
    var ResponsiveFunnelChart = (0, withResponsiveContainer_1.withResponsiveContainer)(FunnelChart_1.FunnelChart);
    // Default x-axis key for grouping traces. Also applicable for PieData and SankeyData where x-axis is not defined.
    var DEFAULT_XAXIS = 'x';
    var FALLBACK_TYPE = 'fallback';
    var useColorMapping = function () {
        var colorMap = React.useRef(new Map());
        return colorMap;
    };
    function renderChart(Renderer, 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    transformer, 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    transformerArgs, commonProps, cellRow, cellColumn) {
        var chartProps = transformer.apply(void 0, transformerArgs);
        return (React.createElement("div", { key: "".concat(cellRow, "_").concat(cellColumn), style: {
                gridRowStart: cellRow,
                gridRowEnd: cellRow + 1,
                gridColumnStart: cellColumn,
                gridColumnEnd: cellColumn + 1,
            } },
            React.createElement(Renderer, tslib_1.__assign({}, chartProps, commonProps))));
    }
    var LineAreaPreTransformOp = function (plotlyInput) {
        var xValues = plotlyInput.data[0].x;
        var isXMonth = (0, chart_utilities_2.isMonthArray)(xValues);
        var renderData = plotlyInput.data;
        if (isXMonth) {
            renderData = plotlyInput.data.map(function (dataPoint) { return (tslib_1.__assign(tslib_1.__assign({}, dataPoint), { x: (0, PlotlySchemaAdapter_1.correctYearMonth)(dataPoint.x) })); });
        }
        return { data: renderData, layout: plotlyInput.layout };
    };
    var chartMap = {
        // PieData category charts
        donut: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToDonutProps,
            renderer: ResponsiveDonutChart,
        },
        // SankeyData category charts
        sankey: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToSankeyProps,
            renderer: ResponsiveSankeyChart,
        },
        // TableData category charts
        table: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToChartTableProps,
            renderer: ResponsiveChartTable,
        },
        // PlotData category charts
        horizontalbar: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToHorizontalBarWithAxisProps,
            renderer: ResponsiveHorizontalBarChartWithAxis,
        },
        groupedverticalbar: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToGVBCProps,
            renderer: ResponsiveGroupedVerticalBarChart,
        },
        verticalstackedbar: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToVSBCProps,
            renderer: ResponsiveVerticalStackedBarChart,
        },
        heatmap: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToHeatmapProps,
            renderer: ResponsiveHeatMapChart,
        },
        gauge: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToGaugeProps,
            renderer: ResponsiveGaugeChart,
        },
        verticalbar: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToVBCProps,
            renderer: ResponsiveVerticalBarChart,
        },
        area: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToAreaChartProps,
            renderer: ResponsiveAreaChart,
            preTransformOperation: LineAreaPreTransformOp,
        },
        line: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToLineChartProps,
            renderer: ResponsiveLineChart,
            preTransformOperation: LineAreaPreTransformOp,
        },
        scatter: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToScatterChartProps,
            renderer: ResponsiveScatterChart,
            preTransformOperation: LineAreaPreTransformOp,
        },
        funnel: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToFunnelChartProps,
            renderer: ResponsiveFunnelChart,
        },
        fallback: {
            transformer: PlotlySchemaAdapter_1.transformPlotlyJsonToVSBCProps,
            renderer: ResponsiveVerticalStackedBarChart,
        },
    };
    /**
     * DeclarativeChart component.
     * {@docCategory DeclarativeChart}
     */
    exports.DeclarativeChart = React.forwardRef(function (props, forwardedRef) {
        var _a;
        var plotlySchema = (0, chart_utilities_2.sanitizeJson)(props.chartSchema).plotlySchema;
        var chart = (0, chart_utilities_2.mapFluentChart)(plotlySchema);
        if (!chart.isValid) {
            throw new Error("Invalid chart schema: ".concat(chart.errorMessage));
        }
        var plotlyInput = plotlySchema;
        try {
            plotlyInput = (0, chart_utilities_1.decodeBase64Fields)(plotlyInput);
        }
        catch (error) {
            throw new Error("Failed to decode plotly schema: ".concat(error));
        }
        var plotlyInputWithValidData = tslib_1.__assign(tslib_1.__assign({}, plotlyInput), { data: chart.validTracesInfo.map(function (trace) { return plotlyInput.data[trace.index]; }) });
        var validTracesFilteredIndex = chart.validTracesInfo.map(function (trace, index) { return ({
            index: index,
            type: trace.type,
        }); });
        var selectedLegends = plotlySchema.selectedLegends;
        var colorMap = useColorMapping();
        var theme = (0, react_1.useTheme)();
        var isDarkTheme = (_a = theme === null || theme === void 0 ? void 0 : theme.isInverted) !== null && _a !== void 0 ? _a : false;
        var chartRef = React.useRef(null);
        var isMultiPlot = React.useRef(false);
        if (!(0, chart_utilities_2.isArrayOrTypedArray)(selectedLegends)) {
            selectedLegends = [];
        }
        var _b = React.useState(selectedLegends), activeLegends = _b[0], setActiveLegends = _b[1];
        var onActiveLegendsChange = function (keys) {
            setActiveLegends(keys);
            if (props.onSchemaChange) {
                props.onSchemaChange({ plotlySchema: { plotlyInput: plotlyInput, selectedLegends: keys } });
            }
        };
        React.useEffect(function () {
            // eslint-disable-next-line @typescript-eslint/no-shadow
            var plotlySchema = (0, chart_utilities_2.sanitizeJson)(props.chartSchema).plotlySchema;
            // eslint-disable-next-line @typescript-eslint/no-shadow
            var selectedLegends = plotlySchema.selectedLegends;
            setActiveLegends(selectedLegends !== null && selectedLegends !== void 0 ? selectedLegends : []);
        }, [props.chartSchema]);
        var multiSelectLegendProps = {
            canSelectMultipleLegends: true,
            onChange: onActiveLegendsChange,
            selectedLegends: activeLegends,
        };
        var commonProps = {
            legendProps: multiSelectLegendProps,
            componentRef: chartRef,
            calloutProps: { layerProps: { eventBubblingEnabled: true } },
        };
        // eslint-disable-next-line @typescript-eslint/no-deprecated
        function createLegends(legendProps) {
            // eslint-disable-next-line react/jsx-no-bind
            return React.createElement(index_12.Legends, tslib_1.__assign({}, legendProps, { selectedLegends: activeLegends, onChange: onActiveLegendsChange }));
        }
        var exportAsImage = React.useCallback(function (opts) {
            return new Promise(function (resolve, reject) {
                if (isMultiPlot.current) {
                    return reject(Error('Exporting multi plot charts as image is not supported'));
                }
                if (!chartRef.current || typeof chartRef.current.toImage !== 'function') {
                    return reject(Error('Chart cannot be exported as image'));
                }
                chartRef.current
                    .toImage(tslib_1.__assign({ background: theme.semanticColors.bodyBackground, scale: 5 }, opts))
                    .then(resolve)
                    .catch(reject);
            });
        }, [theme]);
        React.useImperativeHandle(props.componentRef, function () { return ({
            exportAsImage: exportAsImage,
        }); }, [exportAsImage]);
        if (chart.type === 'scatterpolar') {
            var cartesianProjection = (0, PlotlySchemaAdapter_1.projectPolarToCartesian)(plotlyInputWithValidData);
            plotlyInputWithValidData.data = cartesianProjection.data;
            plotlyInputWithValidData.layout = cartesianProjection.layout;
            validTracesFilteredIndex.forEach(function (trace, index) {
                var _a, _b;
                if (trace.type === 'scatterpolar') {
                    var mode = (_b = (_a = plotlyInputWithValidData.data[index]) === null || _a === void 0 ? void 0 : _a.mode) !== null && _b !== void 0 ? _b : '';
                    if (mode.includes('line')) {
                        validTracesFilteredIndex[index].type = 'line';
                    }
                    else if (mode.includes('markers')) {
                        validTracesFilteredIndex[index].type = 'scatter';
                    }
                    else {
                        validTracesFilteredIndex[index].type = 'line';
                    }
                }
            });
        }
        var groupedTraces = {};
        var nonCartesianTraceCount = 0;
        plotlyInputWithValidData.data.forEach(function (trace, index) {
            var _a;
            var traceKey = '';
            if ((0, PlotlySchemaAdapter_1.isNonPlotType)(chart.validTracesInfo[index].type)) {
                traceKey = "".concat(PlotlySchemaAdapter_1.NON_PLOT_KEY_PREFIX).concat(nonCartesianTraceCount + 1);
                nonCartesianTraceCount++;
            }
            else {
                traceKey = (_a = trace.xaxis) !== null && _a !== void 0 ? _a : DEFAULT_XAXIS;
            }
            if (!groupedTraces[traceKey]) {
                groupedTraces[traceKey] = [];
            }
            groupedTraces[traceKey].push(index);
        });
        isMultiPlot.current = Object.keys(groupedTraces).length > 1;
        var gridProperties = (0, PlotlySchemaAdapter_1.getGridProperties)(plotlyInputWithValidData, isMultiPlot.current, chart.validTracesInfo);
        // Render only one plot if the grid properties cannot determine positioning of multiple plots.
        if (isMultiPlot.current &&
            gridProperties.templateRows === PlotlySchemaAdapter_1.SINGLE_REPEAT &&
            gridProperties.templateColumns === PlotlySchemaAdapter_1.SINGLE_REPEAT) {
            Object.keys(groupedTraces).forEach(function (key, index) {
                if (index > 0) {
                    delete groupedTraces[key];
                }
            });
            isMultiPlot.current = false;
        }
        var allupLegendsProps = (0, PlotlySchemaAdapter_1.getAllupLegendsProps)(plotlyInputWithValidData, colorMap, props.colorwayType, chart.validTracesInfo, isDarkTheme);
        // map through the grouped traces and render the appropriate chart
        return (React.createElement(React.Fragment, null,
            React.createElement("div", { style: {
                    display: 'grid',
                    gridTemplateRows: gridProperties.templateRows,
                    gridTemplateColumns: gridProperties.templateColumns,
                } }, Object.entries(groupedTraces).map(function (_a) {
                var _b, _c, _d;
                var xAxisKey = _a[0], index = _a[1];
                var plotlyInputForGroup = tslib_1.__assign(tslib_1.__assign({}, plotlyInputWithValidData), { data: index.map(function (idx) { return plotlyInputWithValidData.data[idx]; }) });
                var filteredTracesInfo = validTracesFilteredIndex.filter(function (trace) { return index.includes(trace.index); });
                var chartType = validTracesFilteredIndex.some(function (trace) { return trace.type === FALLBACK_TYPE; }) || chart.type === FALLBACK_TYPE
                    ? FALLBACK_TYPE
                    : filteredTracesInfo[0].type;
                if (validTracesFilteredIndex.some(function (trace) { return trace.type === 'line'; }) &&
                    validTracesFilteredIndex.some(function (trace) { return trace.type === 'scatter'; })) {
                    chartType = 'line';
                }
                var chartEntry = chartMap[chartType];
                if (chartEntry) {
                    var transformer = chartEntry.transformer, renderer = chartEntry.renderer, preTransformCondition = chartEntry.preTransformCondition, preTransformOperation = chartEntry.preTransformOperation;
                    if (preTransformCondition === undefined || preTransformCondition(plotlyInputForGroup)) {
                        var transformedInput = preTransformOperation
                            ? preTransformOperation(plotlyInputForGroup)
                            : plotlyInputForGroup;
                        var cellProperties = gridProperties.layout[xAxisKey];
                        return renderChart(renderer, transformer, [transformedInput, isMultiPlot.current, colorMap, props.colorwayType, isDarkTheme], tslib_1.__assign(tslib_1.__assign({}, commonProps), { xAxisAnnotation: cellProperties === null || cellProperties === void 0 ? void 0 : cellProperties.xAnnotation, yAxisAnnotation: cellProperties === null || cellProperties === void 0 ? void 0 : cellProperties.yAnnotation }), (_b = cellProperties === null || cellProperties === void 0 ? void 0 : cellProperties.row) !== null && _b !== void 0 ? _b : 1, (_c = cellProperties === null || cellProperties === void 0 ? void 0 : cellProperties.column) !== null && _c !== void 0 ? _c : 1);
                    }
                    return React.createElement(React.Fragment, null);
                }
                else {
                    throw new Error("Unsupported chart type :".concat((_d = plotlyInputForGroup.data[0]) === null || _d === void 0 ? void 0 : _d.type));
                }
            })),
            isMultiPlot.current && createLegends(allupLegendsProps)));
    });
    exports.DeclarativeChart.displayName = 'DeclarativeChart';
    // eslint-disable-next-line @typescript-eslint/no-deprecated
    exports.DeclarativeChart.defaultProps = {
        colorwayType: 'default',
    };
});
//# sourceMappingURL=DeclarativeChart.js.map