"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeclarativeChart = void 0;
var tslib_1 = require("tslib");
/* eslint-disable @typescript-eslint/naming-convention */
var React = require("react");
var react_1 = require("@fluentui/react");
var index_1 = require("../DonutChart/index");
var index_2 = require("../VerticalStackedBarChart/index");
var chart_utilities_1 = require("@fluentui/chart-utilities");
var PlotlySchemaAdapter_1 = require("./PlotlySchemaAdapter");
var index_3 = require("../LineChart/index");
var index_4 = require("../HorizontalBarChartWithAxis/index");
var index_5 = require("../AreaChart/index");
var index_6 = require("../HeatMapChart/index");
var SankeyChart_1 = require("../SankeyChart/SankeyChart");
var index_7 = require("../GaugeChart/index");
var index_8 = require("../GroupedVerticalBarChart/index");
var index_9 = require("../VerticalBarChart/index");
var withResponsiveContainer_1 = require("../ResponsiveContainer/withResponsiveContainer");
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 useColorMapping = function () {
    var colorMap = React.useRef(new Map());
    return colorMap;
};
/**
 * DeclarativeChart component.
 * {@docCategory DeclarativeChart}
 */
exports.DeclarativeChart = React.forwardRef(function (props, forwardedRef) {
    var _a, _b;
    var plotlySchema = (0, chart_utilities_1.sanitizeJson)(props.chartSchema).plotlySchema;
    var chart = (0, chart_utilities_1.mapFluentChart)(plotlySchema);
    if (!chart.isValid) {
        throw new Error("Invalid chart schema: ".concat(chart.errorMessage));
    }
    var plotlyInput = plotlySchema;
    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);
    if (!(0, chart_utilities_1.isArrayOrTypedArray)(selectedLegends)) {
        selectedLegends = [];
    }
    var _c = React.useState(selectedLegends), activeLegends = _c[0], setActiveLegends = _c[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_1.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 } },
    };
    var renderLineArea = function (plotlyData, isAreaChart) {
        var _a, _b;
        var isScatterMarkers = (_b = (_a = plotlyData[0]) === null || _a === void 0 ? void 0 : _a.mode) === null || _b === void 0 ? void 0 : _b.includes('markers');
        var chartProps = tslib_1.__assign(tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToScatterChartProps)({ data: plotlyData, layout: plotlyInput.layout }, isAreaChart, colorMap, isDarkTheme)), commonProps);
        if (isAreaChart) {
            return React.createElement(ResponsiveAreaChart, tslib_1.__assign({}, chartProps));
        }
        return React.createElement(ResponsiveLineChart, tslib_1.__assign({}, chartProps, { lineMode: isScatterMarkers ? 'scatter' : 'default' }));
    };
    var checkAndRenderChart = function (isAreaChart) {
        if (isAreaChart === void 0) { isAreaChart = false; }
        var fallbackVSBC = false;
        var xValues = plotlyInput.data[0].x;
        var isXDate = (0, chart_utilities_1.isDateArray)(xValues);
        var isXNumber = (0, chart_utilities_1.isNumberArray)(xValues);
        var isXMonth = (0, PlotlySchemaAdapter_1.isMonthArray)(xValues);
        if (isXDate || isXNumber) {
            return renderLineArea(plotlyInput.data, isAreaChart);
        }
        else if (isXMonth) {
            var updatedData = plotlyInput.data.map(function (dataPoint) { return (tslib_1.__assign(tslib_1.__assign({}, dataPoint), { x: (0, PlotlySchemaAdapter_1.correctYearMonth)(dataPoint.x) })); });
            return renderLineArea(updatedData, isAreaChart);
        }
        // Unsupported schema, render as VerticalStackedBarChart
        fallbackVSBC = true;
        return (React.createElement(ResponsiveVerticalStackedBarChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToVSBCProps)(plotlyInput, colorMap, isDarkTheme, fallbackVSBC), commonProps)));
    };
    var exportAsImage = React.useCallback(function (opts) {
        return new Promise(function (resolve, reject) {
            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]);
    switch (chart.type) {
        case 'donut':
            return (React.createElement(ResponsiveDonutChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToDonutProps)(plotlyInput, colorMap, isDarkTheme), commonProps)));
        case 'horizontalbar':
            return (React.createElement(ResponsiveHorizontalBarChartWithAxis, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToHorizontalBarWithAxisProps)(plotlyInput, colorMap, isDarkTheme), commonProps)));
        case 'groupedverticalbar':
            return (React.createElement(ResponsiveGroupedVerticalBarChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToGVBCProps)(plotlyInput, colorMap, isDarkTheme), commonProps)));
        case 'verticalstackedbar':
            return (React.createElement(ResponsiveVerticalStackedBarChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToVSBCProps)(plotlyInput, colorMap, isDarkTheme), commonProps)));
        case 'heatmap':
            return (React.createElement(ResponsiveHeatMapChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToHeatmapProps)(plotlyInput), commonProps, { legendProps: {} })));
        case 'sankey':
            return (React.createElement(ResponsiveSankeyChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToSankeyProps)(plotlyInput, colorMap, isDarkTheme), commonProps)));
        case 'gauge':
            return (React.createElement(ResponsiveGaugeChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToGaugeProps)(plotlyInput, colorMap, isDarkTheme), commonProps)));
        case 'verticalbar':
            return (React.createElement(ResponsiveVerticalBarChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToVBCProps)(plotlyInput, colorMap, isDarkTheme), commonProps)));
        case 'area':
        case 'line':
        case 'fallback':
            // Need recheck for area chart as we don't have ability to check for valid months in previous step
            var isAreaChart = plotlyInput.data.some(function (series) { return series.fill === 'tonexty' || series.fill === 'tozeroy'; });
            return checkAndRenderChart(isAreaChart);
        default:
            throw new Error("Unsupported chart type :".concat((_b = plotlyInput.data[0]) === null || _b === void 0 ? void 0 : _b.type));
    }
});
exports.DeclarativeChart.displayName = 'DeclarativeChart';
//# sourceMappingURL=DeclarativeChart.js.map