"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 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, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
    var plotlySchema = (0, PlotlySchemaAdapter_1.sanitizeJson)(props.chartSchema).plotlySchema;
    var plotlyInput = (function () {
        try {
            return plotlySchema;
        }
        catch (error) {
            throw new Error("Invalid plotly schema: ".concat(error));
        }
    })();
    if (!plotlyInput) {
        throw new Error('Plotly input is null or undefined');
    }
    if (!plotlyInput.data) {
        throw new Error('Plotly input data is null or undefined');
    }
    if (plotlyInput.data.length === 0) {
        throw new Error('Plotly input data is empty');
    }
    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, PlotlySchemaAdapter_1.isArrayOrTypedArray)(selectedLegends)) {
        selectedLegends = [];
    }
    var _t = React.useState(selectedLegends), activeLegends = _t[0], setActiveLegends = _t[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, PlotlySchemaAdapter_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 checkAndRenderChart = function (renderChartJsx, isAreaChart) {
        if (isAreaChart === void 0) { isAreaChart = false; }
        var fallbackVSBC = false;
        var xValues = plotlyInput.data[0].x;
        var isXDate = (0, PlotlySchemaAdapter_1.isDateArray)(xValues);
        var isXNumber = (0, PlotlySchemaAdapter_1.isNumberArray)(xValues);
        var isXMonth = (0, PlotlySchemaAdapter_1.isMonthArray)(xValues);
        if (isXDate || isXNumber) {
            var chartProps = tslib_1.__assign(tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToScatterChartProps)({ data: plotlyInput.data, layout: plotlyInput.layout }, isAreaChart, colorMap, isDarkTheme)), commonProps);
            return renderChartJsx(chartProps);
        }
        else if (isXMonth) {
            var updatedData = plotlyInput.data.map(function (dataPoint) { return (tslib_1.__assign(tslib_1.__assign({}, dataPoint), { x: (0, PlotlySchemaAdapter_1.updateXValues)(dataPoint.x) })); });
            var chartProps = tslib_1.__assign(tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToScatterChartProps)({ data: updatedData, layout: plotlyInput.layout }, isAreaChart, colorMap, isDarkTheme)), commonProps);
            return renderChartJsx(chartProps);
        }
        // Unsupported schema, render as VerticalStackedBarChart
        fallbackVSBC = true;
        return (React.createElement(ResponsiveVerticalStackedBarChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToVSBCProps)(plotlySchema, 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 (plotlyInput.data[0].type) {
        case 'pie':
            return (React.createElement(ResponsiveDonutChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToDonutProps)(plotlySchema, colorMap, isDarkTheme), commonProps)));
        case 'bar':
            var orientation_1 = plotlyInput.data[0].orientation;
            var containsBase = plotlyInput.data.some(function (series) { return series.base !== undefined; });
            if (orientation_1 === 'h' && containsBase) {
                throw new Error('Unsupported chart type: Gantt');
            }
            else if (orientation_1 === 'h' && (0, PlotlySchemaAdapter_1.isNumberArray)(plotlyInput.data[0].x)) {
                return (React.createElement(ResponsiveHorizontalBarChartWithAxis, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToHorizontalBarWithAxisProps)(plotlySchema, colorMap, isDarkTheme), commonProps)));
            }
            else {
                var containsLines = plotlyInput.data.some(function (series) { return series.type === 'scatter' || (0, PlotlySchemaAdapter_1.isLineData)(series); });
                if (['group', 'overlay'].includes((_b = plotlySchema === null || plotlySchema === void 0 ? void 0 : plotlySchema.layout) === null || _b === void 0 ? void 0 : _b.barmode) && !containsLines) {
                    return (React.createElement(ResponsiveGroupedVerticalBarChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToGVBCProps)(plotlySchema, colorMap, isDarkTheme), commonProps)));
                }
                return (React.createElement(ResponsiveVerticalStackedBarChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToVSBCProps)(plotlySchema, colorMap, isDarkTheme), commonProps)));
            }
        case 'scatter':
            if (((_d = (_c = plotlyInput.data[0]) === null || _c === void 0 ? void 0 : _c.mode) === null || _d === void 0 ? void 0 : _d.includes('markers')) && !(0, PlotlySchemaAdapter_1.isNumberArray)(plotlyInput.data[0].y)) {
                throw new Error("Unsupported chart - type :".concat((_e = plotlyInput.data[0]) === null || _e === void 0 ? void 0 : _e.type, ", mode: ").concat((_f = plotlyInput.data[0]) === null || _f === void 0 ? void 0 : _f.mode, "\n          , xAxisType: String or Date"));
            }
            var isAreaChart_1 = plotlyInput.data.some(function (series) { return series.fill === 'tonexty' || series.fill === 'tozeroy'; });
            var isScatterMarkers_1 = (_h = (_g = plotlyInput.data[0]) === null || _g === void 0 ? void 0 : _g.mode) === null || _h === void 0 ? void 0 : _h.includes('markers');
            var renderChartJsx = function (chartProps) {
                if (isAreaChart_1) {
                    return React.createElement(ResponsiveAreaChart, tslib_1.__assign({}, chartProps));
                }
                return React.createElement(ResponsiveLineChart, tslib_1.__assign({}, chartProps, { lineMode: isScatterMarkers_1 ? 'scatter' : 'default' }));
            };
            return checkAndRenderChart(renderChartJsx, isAreaChart_1);
        case 'heatmap':
            return (React.createElement(ResponsiveHeatMapChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToHeatmapProps)(plotlySchema), commonProps, { legendProps: {} })));
        case 'sankey':
            return (React.createElement(ResponsiveSankeyChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToSankeyProps)(plotlySchema, colorMap, isDarkTheme), commonProps)));
        case 'indicator':
        case 'gauge':
            if (((_l = (_k = (_j = plotlyInput.data) === null || _j === void 0 ? void 0 : _j[0]) === null || _k === void 0 ? void 0 : _k.mode) === null || _l === void 0 ? void 0 : _l.includes('gauge')) || ((_o = (_m = plotlyInput.data) === null || _m === void 0 ? void 0 : _m[0]) === null || _o === void 0 ? void 0 : _o.type) === 'gauge') {
                return (React.createElement(ResponsiveGaugeChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToGaugeProps)(plotlySchema, colorMap, isDarkTheme), commonProps)));
            }
            throw new Error("Unsupported chart - type: ".concat((_p = plotlyInput.data[0]) === null || _p === void 0 ? void 0 : _p.type, ", mode: ").concat((_q = plotlyInput.data[0]) === null || _q === void 0 ? void 0 : _q.mode));
        case 'histogram':
            return (React.createElement(ResponsiveVerticalBarChart, tslib_1.__assign({}, (0, PlotlySchemaAdapter_1.transformPlotlyJsonToVBCProps)(plotlySchema, colorMap, isDarkTheme), commonProps)));
        case 'contour':
            throw new Error("Unsupported chart - type: ".concat((_r = plotlyInput.data[0]) === null || _r === void 0 ? void 0 : _r.type));
        default:
            var xValues = plotlyInput.data[0].x;
            var yValues = plotlyInput.data[0].y;
            if (xValues && yValues && xValues.length > 0 && yValues.length > 0) {
                var renderLineChartJsx = function (chartProps) {
                    return React.createElement(ResponsiveLineChart, tslib_1.__assign({}, chartProps));
                };
                return checkAndRenderChart(renderLineChartJsx);
            }
            throw new Error("Unsupported chart type :".concat((_s = plotlyInput.data[0]) === null || _s === void 0 ? void 0 : _s.type));
    }
});
exports.DeclarativeChart.displayName = 'DeclarativeChart';
//# sourceMappingURL=DeclarativeChart.js.map