"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getValidXYRanges = exports.getNumberAtIndexOrDefault = exports.isInvalidValue = exports.findArrayAttributes = exports.projectPolarToCartesian = exports.transformPlotlyJsonToChartTableProps = exports.transformPlotlyJsonToGaugeProps = exports.transformPlotlyJsonToSankeyProps = exports.transformPlotlyJsonToHeatmapProps = exports.transformPlotlyJsonToHorizontalBarWithAxisProps = exports.transformPlotlyJsonToScatterChartProps = exports.transformPlotlyJsonToVBCProps = exports.transformPlotlyJsonToGVBCProps = exports.transformPlotlyJsonToVSBCProps = exports.transformPlotlyJsonToDonutProps = exports._getGaugeAxisColor = exports.correctYearMonth = exports.isMonthArray = void 0;
var tslib_1 = require("tslib");
var d3_array_1 = require("d3-array");
var d3_scale_1 = require("d3-scale");
var colors_1 = require("../../utilities/colors");
var index_1 = require("../GaugeChart/index");
var utilities_1 = require("../../utilities/utilities");
var chart_utilities_1 = require("@fluentui/chart-utilities");
var d3_time_format_1 = require("d3-time-format");
var d3_shape_1 = require("d3-shape");
var PlotlyColorAdapter_1 = require("./PlotlyColorAdapter");
var dashOptions = {
    dot: {
        strokeDasharray: '1, 5',
        strokeLinecap: 'round',
        strokeWidth: '2',
        lineBorderWidth: '4',
    },
    dash: {
        strokeDasharray: '5, 5',
        strokeLinecap: 'butt',
        strokeWidth: '2',
        lineBorderWidth: '4',
    },
    longdash: {
        strokeDasharray: '10, 5',
        strokeLinecap: 'butt',
        strokeWidth: '2',
        lineBorderWidth: '4',
    },
    dashdot: {
        strokeDasharray: '5, 5, 1, 5',
        strokeLinecap: 'butt',
        strokeWidth: '2',
        lineBorderWidth: '4',
    },
    longdashdot: {
        strokeDasharray: '10, 5, 1, 5',
        strokeLinecap: 'butt',
        strokeWidth: '2',
        lineBorderWidth: '4',
    },
    solid: {
        strokeDasharray: '0',
        strokeLinecap: 'butt',
        strokeWidth: '2',
        lineBorderWidth: '4',
    },
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var isMonth = function (possiblyMonthValue) {
    var parseFullMonth = (0, d3_time_format_1.timeParse)('%B');
    var parseShortMonth = (0, d3_time_format_1.timeParse)('%b');
    return parseFullMonth(possiblyMonthValue) !== null || parseShortMonth(possiblyMonthValue) !== null;
};
var isMonthArray = function (data) {
    /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
    return (0, chart_utilities_1.isArrayOfType)(data, function (value) { return isMonth(value) || value === null; });
};
exports.isMonthArray = isMonthArray;
function getTitles(layout) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
    var titles = {
        chartTitle: typeof (layout === null || layout === void 0 ? void 0 : layout.title) === 'string' ? layout.title : (_b = (_a = layout === null || layout === void 0 ? void 0 : layout.title) === null || _a === void 0 ? void 0 : _a.text) !== null && _b !== void 0 ? _b : '',
        xAxisTitle: typeof ((_c = layout === null || layout === void 0 ? void 0 : layout.xaxis) === null || _c === void 0 ? void 0 : _c.title) === 'string' ? (_d = layout === null || layout === void 0 ? void 0 : layout.xaxis) === null || _d === void 0 ? void 0 : _d.title : (_g = (_f = (_e = layout === null || layout === void 0 ? void 0 : layout.xaxis) === null || _e === void 0 ? void 0 : _e.title) === null || _f === void 0 ? void 0 : _f.text) !== null && _g !== void 0 ? _g : '',
        yAxisTitle: typeof ((_h = layout === null || layout === void 0 ? void 0 : layout.yaxis) === null || _h === void 0 ? void 0 : _h.title) === 'string' ? (_j = layout === null || layout === void 0 ? void 0 : layout.yaxis) === null || _j === void 0 ? void 0 : _j.title : (_m = (_l = (_k = layout === null || layout === void 0 ? void 0 : layout.yaxis) === null || _k === void 0 ? void 0 : _k.title) === null || _l === void 0 ? void 0 : _l.text) !== null && _m !== void 0 ? _m : '',
    };
    return titles;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var correctYearMonth = function (xValues) {
    var presentYear = new Date().getFullYear();
    if (xValues.length > 0 && Array.isArray(xValues[0])) {
        throw new Error('updateXValues:: 2D array not supported');
    }
    var dates = xValues.map(function (possiblyMonthValue) {
        var parsedDate = "".concat(possiblyMonthValue, " 01, ").concat(presentYear);
        return (0, chart_utilities_1.isDate)(parsedDate) ? new Date(parsedDate) : null;
    });
    var filteredDateIndexPairs = dates.map(function (date, index) { return [date, index]; }).filter(function (_a) {
        var date = _a[0];
        return date !== null;
    });
    for (var i = filteredDateIndexPairs.length - 1; i > 0; i--) {
        var currentDate = filteredDateIndexPairs[i][0];
        var previousDate = filteredDateIndexPairs[i - 1][0];
        var currentMonth = currentDate.getMonth();
        var previousMonth = previousDate.getMonth();
        var currentYear = currentDate.getFullYear();
        var previousYear = previousDate.getFullYear();
        if (previousMonth >= currentMonth) {
            filteredDateIndexPairs[i - 1][0].setFullYear(currentYear - 1);
        }
        else if (previousYear > currentYear) {
            filteredDateIndexPairs[i - 1][0].setFullYear(currentYear);
        }
        dates[filteredDateIndexPairs[i - 1][1]] = filteredDateIndexPairs[i - 1][0];
    }
    xValues = xValues.map(function (month, index) {
        if (dates[index] === null) {
            return null;
        }
        return "".concat(month, " 01, ").concat(dates[index].getFullYear());
    });
    return xValues;
};
exports.correctYearMonth = correctYearMonth;
var usesSecondaryYScale = function (series) {
    return series.yaxis === 'y2';
};
var getSecondaryYAxisValues = function (data, layout, maxAllowedMinY, minAllowedMaxY) {
    var _a, _b, _c, _d;
    var containsSecondaryYAxis = false;
    var yMinValue;
    var yMaxValue;
    data.forEach(function (series) {
        if (usesSecondaryYScale(series)) {
            containsSecondaryYAxis = true;
            var yValues = series.y;
            if (yValues) {
                yMinValue = Math.min.apply(Math, yValues);
                yMaxValue = Math.max.apply(Math, yValues);
            }
        }
    });
    if (!containsSecondaryYAxis) {
        return {};
    }
    if (typeof yMinValue === 'number' && typeof maxAllowedMinY === 'number') {
        yMinValue = Math.min(yMinValue, maxAllowedMinY);
    }
    if (typeof yMaxValue === 'number' && typeof minAllowedMaxY === 'number') {
        yMaxValue = Math.max(yMaxValue, minAllowedMaxY);
    }
    if ((_a = layout === null || layout === void 0 ? void 0 : layout.yaxis2) === null || _a === void 0 ? void 0 : _a.range) {
        yMinValue = layout.yaxis2.range[0];
        yMaxValue = layout.yaxis2.range[1];
    }
    return {
        secondaryYAxistitle: typeof ((_b = layout === null || layout === void 0 ? void 0 : layout.yaxis2) === null || _b === void 0 ? void 0 : _b.title) === 'string'
            ? layout.yaxis2.title
            : typeof ((_d = (_c = layout === null || layout === void 0 ? void 0 : layout.yaxis2) === null || _c === void 0 ? void 0 : _c.title) === null || _d === void 0 ? void 0 : _d.text) === 'string'
                ? layout.yaxis2.title.text
                : undefined,
        secondaryYScaleOptions: {
            yMinValue: yMinValue,
            yMaxValue: yMaxValue,
        },
    };
};
var _getGaugeAxisColor = function (colorway, colorwayType, color, colorMap, isDarkTheme) {
    var extractedColors = (0, PlotlyColorAdapter_1.extractColor)(colorway, colorwayType, color, colorMap, isDarkTheme);
    return (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, 0, '', colorMap, isDarkTheme);
};
exports._getGaugeAxisColor = _getGaugeAxisColor;
var transformPlotlyJsonToDonutProps = function (input, colorMap, colorwayType, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
    var firstData = input.data[0];
    // extract colors for each series only once
    // use piecolorway if available
    // otherwise, default to colorway from template
    var colors = (0, PlotlyColorAdapter_1.extractColor)((_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.piecolorway) !== null && _b !== void 0 ? _b : (_e = (_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.template) === null || _d === void 0 ? void 0 : _d.layout) === null || _e === void 0 ? void 0 : _e.colorway, colorwayType, (_g = (_f = input.layout) === null || _f === void 0 ? void 0 : _f.piecolorway) !== null && _g !== void 0 ? _g : (_h = firstData === null || firstData === void 0 ? void 0 : firstData.marker) === null || _h === void 0 ? void 0 : _h.colors, colorMap, isDarkTheme);
    var mapLegendToDataPoint = {};
    (_j = firstData.labels) === null || _j === void 0 ? void 0 : _j.forEach(function (label, index) {
        var value = (0, exports.getNumberAtIndexOrDefault)(firstData.values, index);
        if ((0, exports.isInvalidValue)(value) || value < 0) {
            return;
        }
        var legend = "".concat(label);
        // resolve color for each legend from the extracted colors
        var color = (0, PlotlyColorAdapter_1.resolveColor)(colors, index, legend, colorMap, isDarkTheme);
        if (!mapLegendToDataPoint[legend]) {
            mapLegendToDataPoint[legend] = {
                legend: legend,
                data: value,
                color: color,
            };
        }
        else {
            mapLegendToDataPoint[legend].data += value;
        }
    });
    var width = (_l = (_k = input.layout) === null || _k === void 0 ? void 0 : _k.width) !== null && _l !== void 0 ? _l : 440;
    var height = (_o = (_m = input.layout) === null || _m === void 0 ? void 0 : _m.height) !== null && _o !== void 0 ? _o : 220;
    var hideLabels = firstData.textinfo
        ? !['value', 'percent', 'label+percent'].includes(firstData.textinfo)
        : false;
    var donutMarginHorizontal = hideLabels ? 0 : 80;
    var donutMarginVertical = 40 + (hideLabels ? 0 : 40);
    var innerRadius = firstData.hole
        ? firstData.hole * (Math.min(width - donutMarginHorizontal, height - donutMarginVertical) / 2)
        : 0;
    var chartTitle = getTitles(input.layout).chartTitle;
    return {
        data: {
            chartTitle: chartTitle,
            chartData: Object.values(mapLegendToDataPoint),
        },
        hideLegend: ((_p = input.layout) === null || _p === void 0 ? void 0 : _p.showlegend) === false ? true : false,
        width: (_q = input.layout) === null || _q === void 0 ? void 0 : _q.width,
        height: height,
        innerRadius: innerRadius,
        hideLabels: hideLabels,
        showLabelsInPercent: firstData.textinfo ? ['percent', 'label+percent'].includes(firstData.textinfo) : true,
        roundCorners: true,
    };
};
exports.transformPlotlyJsonToDonutProps = transformPlotlyJsonToDonutProps;
var transformPlotlyJsonToVSBCProps = function (input, colorMap, colorwayType, isDarkTheme, fallbackVSBC) {
    var _a, _b, _c;
    var mapXToDataPoints = {};
    var yMaxValue = 0;
    var yMinValue = 0;
    var secondaryYAxisValues = getSecondaryYAxisValues(input.data, input.layout);
    var _d = getLegendProps(input.data, input.layout), legends = _d.legends, hideLegend = _d.hideLegend;
    input.data.forEach(function (series, index1) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        var isXYearCategory = (0, chart_utilities_1.isYearArray)(series.x); // Consider year as categorical not numeric continuous axis
        // extract bar colors for each series only once
        var extractedBarColors = (0, PlotlyColorAdapter_1.extractColor)((_c = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.template) === null || _b === void 0 ? void 0 : _b.layout) === null || _c === void 0 ? void 0 : _c.colorway, colorwayType, (_d = series.marker) === null || _d === void 0 ? void 0 : _d.color, colorMap, isDarkTheme);
        // extract line colors for each series only once
        var extractedLineColors = (0, PlotlyColorAdapter_1.extractColor)((_g = (_f = (_e = input.layout) === null || _e === void 0 ? void 0 : _e.template) === null || _f === void 0 ? void 0 : _f.layout) === null || _g === void 0 ? void 0 : _g.colorway, colorwayType, (_h = series.line) === null || _h === void 0 ? void 0 : _h.color, colorMap, isDarkTheme);
        var validXYRanges = (0, exports.getValidXYRanges)(series);
        validXYRanges.forEach(function (_a, rangeIdx) {
            var rangeStart = _a[0], rangeEnd = _a[1];
            var rangeXValues = series.x.slice(rangeStart, rangeEnd);
            var rangeYValues = series.y.slice(rangeStart, rangeEnd);
            rangeXValues.forEach(function (x, index2) {
                var _a, _b;
                if (!mapXToDataPoints[x]) {
                    mapXToDataPoints[x] = { xAxisPoint: isXYearCategory ? x.toString() : x, chartData: [], lineData: [] };
                }
                var legend = legends[index1];
                // resolve color for each legend's bars from the extracted colors
                var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedBarColors, index1, legend, colorMap, isDarkTheme);
                var yVal = rangeYValues[index2];
                if (series.type === 'bar') {
                    mapXToDataPoints[x].chartData.push({
                        legend: legend,
                        data: yVal,
                        color: color,
                    });
                    yMaxValue = Math.max(yMaxValue, yVal);
                }
                else if (series.type === 'scatter' || !!fallbackVSBC) {
                    var lineColor = (0, PlotlyColorAdapter_1.resolveColor)(extractedLineColors, index1, legend, colorMap, isDarkTheme);
                    var lineOptions = getLineOptions(series.line);
                    var dashType = ((_a = series.line) === null || _a === void 0 ? void 0 : _a.dash) || 'solid';
                    var legendShape = dashType === 'dot' || dashType === 'dash' || dashType === 'dashdot'
                        ? 'dottedLine'
                        : ((_b = series.mode) === null || _b === void 0 ? void 0 : _b.includes('markers'))
                            ? 'circle'
                            : 'default';
                    mapXToDataPoints[x].lineData.push({
                        legend: legend + (validXYRanges.length > 1 ? ".".concat(rangeIdx + 1) : ''),
                        legendShape: legendShape,
                        y: yVal,
                        color: lineColor,
                        lineOptions: tslib_1.__assign(tslib_1.__assign({}, (lineOptions !== null && lineOptions !== void 0 ? lineOptions : {})), { mode: series.mode }),
                        useSecondaryYScale: usesSecondaryYScale(series),
                    });
                    if (!usesSecondaryYScale(series)) {
                        yMaxValue = Math.max(yMaxValue, yVal);
                        yMinValue = Math.min(yMinValue, yVal);
                    }
                }
            });
        });
    });
    var _e = getTitles(input.layout), chartTitle = _e.chartTitle, xAxisTitle = _e.xAxisTitle, yAxisTitle = _e.yAxisTitle;
    return tslib_1.__assign(tslib_1.__assign({ data: Object.values(mapXToDataPoints), width: (_a = input.layout) === null || _a === void 0 ? void 0 : _a.width, height: (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.height) !== null && _c !== void 0 ? _c : 350, barWidth: 'auto', yMaxValue: yMaxValue, yMinValue: yMinValue, chartTitle: chartTitle, xAxisTitle: xAxisTitle, yAxisTitle: yAxisTitle, mode: 'plotly' }, secondaryYAxisValues), { hideTickOverlap: true, hideLegend: hideLegend, roundCorners: true, supportNegativeData: true, barGapMax: 2 });
};
exports.transformPlotlyJsonToVSBCProps = transformPlotlyJsonToVSBCProps;
var transformPlotlyJsonToGVBCProps = function (input, colorMap, colorwayType, isDarkTheme) {
    var _a, _b, _c;
    var mapXToDataPoints = {};
    var secondaryYAxisValues = getSecondaryYAxisValues(input.data, input.layout, 0, 0);
    var _d = getLegendProps(input.data, input.layout), legends = _d.legends, hideLegend = _d.hideLegend;
    input.data.forEach(function (series, index1) {
        var _a, _b, _c, _d, _e;
        // extract colors for each series only once
        var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_c = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.template) === null || _b === void 0 ? void 0 : _b.layout) === null || _c === void 0 ? void 0 : _c.colorway, colorwayType, (_d = series.marker) === null || _d === void 0 ? void 0 : _d.color, colorMap, isDarkTheme);
        (_e = series.x) === null || _e === void 0 ? void 0 : _e.forEach(function (x, xIndex) {
            var _a;
            if ((0, exports.isInvalidValue)(x) || (0, exports.isInvalidValue)((_a = series.y) === null || _a === void 0 ? void 0 : _a[xIndex])) {
                return;
            }
            if (!mapXToDataPoints[x]) {
                mapXToDataPoints[x] = { name: x.toString(), series: [] };
            }
            if (series.type === 'bar') {
                var legend = legends[index1];
                // resolve color for each legend's bars from the extracted colors
                var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, index1, legend, colorMap, isDarkTheme);
                mapXToDataPoints[x].series.push({
                    key: legend,
                    data: series.y[xIndex],
                    xAxisCalloutData: x,
                    color: color,
                    legend: legend,
                    useSecondaryYScale: usesSecondaryYScale(series),
                });
            }
        });
    });
    var _e = getTitles(input.layout), chartTitle = _e.chartTitle, xAxisTitle = _e.xAxisTitle, yAxisTitle = _e.yAxisTitle;
    return tslib_1.__assign(tslib_1.__assign({ data: Object.values(mapXToDataPoints), width: (_a = input.layout) === null || _a === void 0 ? void 0 : _a.width, height: (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.height) !== null && _c !== void 0 ? _c : 350, barwidth: 'auto', chartTitle: chartTitle, xAxisTitle: xAxisTitle, yAxisTitle: yAxisTitle, mode: 'plotly' }, secondaryYAxisValues), { hideTickOverlap: true, hideLegend: hideLegend, roundCorners: true });
};
exports.transformPlotlyJsonToGVBCProps = transformPlotlyJsonToGVBCProps;
var transformPlotlyJsonToVBCProps = function (input, colorMap, colorwayType, isDarkTheme) {
    var _a, _b, _c;
    var vbcData = [];
    var _d = getLegendProps(input.data, input.layout), legends = _d.legends, hideLegend = _d.hideLegend;
    input.data.forEach(function (series, seriesIdx) {
        var _a, _b, _c, _d, _e, _f, _g;
        if (!series.x) {
            return;
        }
        // extract colors for each series only once
        var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_c = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.template) === null || _b === void 0 ? void 0 : _b.layout) === null || _c === void 0 ? void 0 : _c.colorway, colorwayType, (_d = series.marker) === null || _d === void 0 ? void 0 : _d.color, colorMap, isDarkTheme);
        var xValues = [];
        var yValues = [];
        series.x.forEach(function (xVal, index) {
            var yVal = (0, exports.getNumberAtIndexOrDefault)(series.y, index);
            if ((0, exports.isInvalidValue)(xVal) || (0, exports.isInvalidValue)(yVal)) {
                return;
            }
            xValues.push(xVal);
            yValues.push(yVal);
        });
        var isXString = isStringArray(xValues);
        // TODO: In case of a single bin, add an empty bin of the same size to prevent the
        // default bar width from being used and ensure the bar spans the full intended range.
        var xBins = createBins(xValues, (_e = series.xbins) === null || _e === void 0 ? void 0 : _e.start, (_f = series.xbins) === null || _f === void 0 ? void 0 : _f.end, (_g = series.xbins) === null || _g === void 0 ? void 0 : _g.size);
        var yBins = xBins.map(function () { return []; });
        var total = 0;
        xValues.forEach(function (xVal, index) {
            var binIdx = findBinIndex(xBins, xVal, isXString);
            if (binIdx !== -1) {
                yBins[binIdx].push(yValues[index]);
            }
        });
        var y = yBins.map(function (bin) {
            var yVal = calculateHistFunc(series.histfunc, bin);
            total += yVal;
            return yVal;
        });
        xBins.forEach(function (bin, index) {
            var legend = legends[seriesIdx];
            // resolve color for each legend's bars from the extracted colors
            var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, seriesIdx, legend, colorMap, isDarkTheme);
            var yVal = calculateHistNorm(series.histnorm, y[index], total, isXString ? bin.length : getBinSize(bin));
            vbcData.push(tslib_1.__assign({ x: isXString ? bin.join(', ') : getBinCenter(bin), y: yVal, legend: legend, color: color }, (isXString
                ? {}
                : { xAxisCalloutData: "[".concat(bin.x0, " - ").concat(bin.x1, ")") })));
        });
    });
    var _e = getTitles(input.layout), chartTitle = _e.chartTitle, xAxisTitle = _e.xAxisTitle, yAxisTitle = _e.yAxisTitle;
    return {
        data: vbcData,
        width: (_a = input.layout) === null || _a === void 0 ? void 0 : _a.width,
        height: (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.height) !== null && _c !== void 0 ? _c : 350,
        supportNegativeData: true,
        chartTitle: chartTitle,
        xAxisTitle: xAxisTitle,
        yAxisTitle: yAxisTitle,
        mode: 'histogram',
        hideTickOverlap: true,
        maxBarWidth: 50,
        hideLegend: hideLegend,
        roundCorners: true,
    };
};
exports.transformPlotlyJsonToVBCProps = transformPlotlyJsonToVBCProps;
var transformPlotlyJsonToScatterChartProps = function (input, isAreaChart, isScatterMarkers, colorMap, colorwayType, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f;
    var secondaryYAxisValues = getSecondaryYAxisValues(input.data, input.layout, isAreaChart ? 0 : undefined, isAreaChart ? 0 : undefined);
    var mode = 'tonexty';
    var _g = getLegendProps(input.data, input.layout), legends = _g.legends, hideLegend = _g.hideLegend;
    var chartData = input.data
        .map(function (series, index) {
        var _a, _b, _c, _d, _e, _f, _g;
        // extract colors for each series only once
        var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_c = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.template) === null || _b === void 0 ? void 0 : _b.layout) === null || _c === void 0 ? void 0 : _c.colorway, colorwayType, isScatterMarkers ? (_d = series.marker) === null || _d === void 0 ? void 0 : _d.color : (_e = series.line) === null || _e === void 0 ? void 0 : _e.color, colorMap, isDarkTheme);
        var xValues = series.x;
        var isString = isStringArray(xValues);
        var isXDate = (0, chart_utilities_1.isDateArray)(xValues);
        var isXNumber = (0, chart_utilities_1.isNumberArray)(xValues);
        var legend = legends[index];
        // resolve color for each legend's lines from the extracted colors
        var seriesColor = (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, index, legend, colorMap, isDarkTheme);
        mode = series.fill === 'tozeroy' ? 'tozeroy' : 'tonexty';
        var lineOptions = getLineOptions(series.line);
        var dashType = ((_f = series.line) === null || _f === void 0 ? void 0 : _f.dash) || 'solid';
        var legendShape = dashType === 'dot' || dashType === 'dash' || dashType === 'dashdot'
            ? 'dottedLine'
            : ((_g = series.mode) === null || _g === void 0 ? void 0 : _g.includes('markers'))
                ? 'circle'
                : 'default';
        var validXYRanges = (0, exports.getValidXYRanges)(series);
        return validXYRanges.map(function (_a, rangeIdx) {
            var _b;
            var rangeStart = _a[0], rangeEnd = _a[1];
            var rangeXValues = xValues.slice(rangeStart, rangeEnd);
            var rangeYValues = series.y.slice(rangeStart, rangeEnd);
            var markerSizes = (0, chart_utilities_1.isArrayOrTypedArray)((_b = series.marker) === null || _b === void 0 ? void 0 : _b.size)
                ? series.marker.size.slice(rangeStart, rangeEnd)
                : [];
            return {
                legend: legend,
                legendShape: legendShape,
                data: rangeXValues.map(function (x, i) {
                    var _a, _b;
                    return (tslib_1.__assign({ x: isString ? (isXDate ? new Date(x) : isXNumber ? parseFloat(x) : x) : x, y: rangeYValues[i] }, (Array.isArray((_a = series.marker) === null || _a === void 0 ? void 0 : _a.size)
                        ? { markerSize: markerSizes[i] }
                        : typeof ((_b = series.marker) === null || _b === void 0 ? void 0 : _b.size) === 'number'
                            ? { markerSize: series.marker.size }
                            : {})));
                }),
                color: seriesColor,
                lineOptions: tslib_1.__assign(tslib_1.__assign({}, (lineOptions !== null && lineOptions !== void 0 ? lineOptions : {})), { mode: series.mode }),
                useSecondaryYScale: usesSecondaryYScale(series),
            };
        });
    })
        .flat();
    var yMinMaxValues = (0, utilities_1.findNumericMinMaxOfY)(chartData);
    var _h = getTitles(input.layout), chartTitle = _h.chartTitle, xAxisTitle = _h.xAxisTitle, yAxisTitle = _h.yAxisTitle;
    var numDataPoints = chartData.reduce(function (total, lineChartPoints) { return total + lineChartPoints.data.length; }, 0);
    var chartProps = {
        chartTitle: chartTitle,
        lineChartData: chartData,
    };
    if (isAreaChart) {
        return tslib_1.__assign(tslib_1.__assign({ data: chartProps, supportNegativeData: true, xAxisTitle: xAxisTitle, yAxisTitle: yAxisTitle }, secondaryYAxisValues), { mode: mode, width: (_a = input.layout) === null || _a === void 0 ? void 0 : _a.width, height: (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.height) !== null && _c !== void 0 ? _c : 350, hideTickOverlap: true, hideLegend: hideLegend, useUTC: false, optimizeLargeData: numDataPoints > 1000 });
    }
    else {
        return tslib_1.__assign(tslib_1.__assign({ data: chartProps, supportNegativeData: true, xAxisTitle: xAxisTitle, yAxisTitle: yAxisTitle }, secondaryYAxisValues), { roundedTicks: true, yMinValue: yMinMaxValues.startValue, yMaxValue: yMinMaxValues.endValue, width: (_d = input.layout) === null || _d === void 0 ? void 0 : _d.width, height: (_f = (_e = input.layout) === null || _e === void 0 ? void 0 : _e.height) !== null && _f !== void 0 ? _f : 350, hideTickOverlap: true, enableReflow: false, hideLegend: hideLegend, useUTC: false, optimizeLargeData: numDataPoints > 1000 });
    }
};
exports.transformPlotlyJsonToScatterChartProps = transformPlotlyJsonToScatterChartProps;
var transformPlotlyJsonToHorizontalBarWithAxisProps = function (input, colorMap, colorwayType, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
    var _s = getLegendProps(input.data, input.layout), legends = _s.legends, hideLegend = _s.hideLegend;
    var chartData = input.data
        .map(function (series, index) {
        var _a, _b, _c, _d;
        // extract colors for each series only once
        var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_c = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.template) === null || _b === void 0 ? void 0 : _b.layout) === null || _c === void 0 ? void 0 : _c.colorway, colorwayType, (_d = series.marker) === null || _d === void 0 ? void 0 : _d.color, colorMap, isDarkTheme);
        var legend = legends[index];
        // resolve color for each legend's bars from the extracted colors
        var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, index, legend, colorMap, isDarkTheme);
        return series.y
            .map(function (yValue, i) {
            var _a;
            if ((0, exports.isInvalidValue)((_a = series.x) === null || _a === void 0 ? void 0 : _a[i]) || (0, exports.isInvalidValue)(yValue)) {
                return null;
            }
            return {
                x: series.x[i],
                y: yValue,
                legend: legend,
                color: color,
            };
        })
            .filter(function (point) { return point !== null; });
    })
        .reverse()
        .flat()
        //reversing the order to invert the Y bars order as required by plotly.
        .reverse();
    var chartHeight = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.height) !== null && _b !== void 0 ? _b : 450;
    var margin = (_e = (_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.margin) === null || _d === void 0 ? void 0 : _d.l) !== null && _e !== void 0 ? _e : 0;
    var padding = (_h = (_g = (_f = input.layout) === null || _f === void 0 ? void 0 : _f.margin) === null || _g === void 0 ? void 0 : _g.pad) !== null && _h !== void 0 ? _h : 0;
    var availableHeight = chartHeight - margin - padding;
    var numberOfRows = new Set(chartData.map(function (d) { return d.y; })).size || 1;
    var scalingFactor = 0.01;
    var gapFactor = 1 / (1 + scalingFactor * numberOfRows);
    var barHeight = availableHeight / (numberOfRows * (1 + gapFactor));
    var _t = getTitles(input.layout), chartTitle = _t.chartTitle, xAxisTitle = _t.xAxisTitle, yAxisTitle = _t.yAxisTitle;
    return {
        data: chartData,
        chartTitle: chartTitle,
        xAxisTitle: xAxisTitle,
        yAxisTitle: yAxisTitle,
        secondaryYAxistitle: typeof ((_k = (_j = input.layout) === null || _j === void 0 ? void 0 : _j.yaxis2) === null || _k === void 0 ? void 0 : _k.title) === 'string'
            ? (_m = (_l = input.layout) === null || _l === void 0 ? void 0 : _l.yaxis2) === null || _m === void 0 ? void 0 : _m.title
            : ((_q = (_p = (_o = input.layout) === null || _o === void 0 ? void 0 : _o.yaxis2) === null || _p === void 0 ? void 0 : _p.title) === null || _q === void 0 ? void 0 : _q.text) || '',
        barHeight: barHeight,
        showYAxisLables: true,
        height: chartHeight,
        width: (_r = input.layout) === null || _r === void 0 ? void 0 : _r.width,
        hideTickOverlap: true,
        hideLegend: hideLegend,
        noOfCharsToTruncate: 20,
        showYAxisLablesTooltip: true,
        roundCorners: true,
    };
};
exports.transformPlotlyJsonToHorizontalBarWithAxisProps = transformPlotlyJsonToHorizontalBarWithAxisProps;
var transformPlotlyJsonToHeatmapProps = function (input) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8;
    var firstData = input.data[0];
    var heatmapDataPoints = [];
    var zMin = Number.POSITIVE_INFINITY;
    var zMax = Number.NEGATIVE_INFINITY;
    if (firstData.type === 'histogram2d') {
        var xValues_1 = [];
        var yValues_1 = [];
        var zValues_1 = [];
        (_a = firstData.x) === null || _a === void 0 ? void 0 : _a.forEach(function (xVal, index) {
            var _a;
            var zVal = (0, exports.getNumberAtIndexOrDefault)(firstData.z, index);
            if ((0, exports.isInvalidValue)(xVal) || (0, exports.isInvalidValue)((_a = firstData.y) === null || _a === void 0 ? void 0 : _a[index]) || (0, exports.isInvalidValue)(zVal)) {
                return;
            }
            xValues_1.push(xVal);
            yValues_1.push(firstData.y[index]);
            zValues_1.push(zVal);
        });
        var isXString_1 = isStringArray(xValues_1);
        var isYString_1 = isStringArray(yValues_1);
        var xBins_1 = createBins(xValues_1, (_b = firstData.xbins) === null || _b === void 0 ? void 0 : _b.start, (_c = firstData.xbins) === null || _c === void 0 ? void 0 : _c.end, (_d = firstData.xbins) === null || _d === void 0 ? void 0 : _d.size);
        var yBins_1 = createBins(yValues_1, (_e = firstData.ybins) === null || _e === void 0 ? void 0 : _e.start, (_f = firstData.ybins) === null || _f === void 0 ? void 0 : _f.end, (_g = firstData.ybins) === null || _g === void 0 ? void 0 : _g.size);
        var zBins_1 = yBins_1.map(function () { return xBins_1.map(function () { return []; }); });
        var total_1 = 0;
        xValues_1.forEach(function (xVal, index) {
            var xBinIdx = findBinIndex(xBins_1, xVal, isXString_1);
            var yBinIdx = findBinIndex(yBins_1, yValues_1[index], isYString_1);
            if (xBinIdx !== -1 && yBinIdx !== -1) {
                zBins_1[yBinIdx][xBinIdx].push(zValues_1[index]);
            }
        });
        var z_1 = zBins_1.map(function (row) {
            return row.map(function (bin) {
                var zVal = calculateHistFunc(firstData.histfunc, bin);
                total_1 += zVal;
                return zVal;
            });
        });
        xBins_1.forEach(function (xBin, xIdx) {
            yBins_1.forEach(function (yBin, yIdx) {
                var zVal = calculateHistNorm(firstData.histnorm, z_1[yIdx][xIdx], total_1, isXString_1 ? xBin.length : getBinSize(xBin), isYString_1 ? yBin.length : getBinSize(yBin));
                heatmapDataPoints.push({
                    x: isXString_1 ? xBin.join(', ') : getBinCenter(xBin),
                    y: isYString_1 ? yBin.join(', ') : getBinCenter(yBin),
                    value: zVal,
                    rectText: zVal,
                });
                if (typeof zVal === 'number') {
                    zMin = Math.min(zMin, zVal);
                    zMax = Math.max(zMax, zVal);
                }
            });
        });
    }
    else {
        (_h = firstData.x) === null || _h === void 0 ? void 0 : _h.forEach(function (xVal, xIdx) {
            var _a;
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            (_a = firstData.y) === null || _a === void 0 ? void 0 : _a.forEach(function (yVal, yIdx) {
                var _a, _b, _c, _d, _e, _f;
                var zVal = (_b = (_a = firstData.z) === null || _a === void 0 ? void 0 : _a[yIdx]) === null || _b === void 0 ? void 0 : _b[xIdx];
                heatmapDataPoints.push({
                    x: ((_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.xaxis) === null || _d === void 0 ? void 0 : _d.type) === 'date' ? xVal : xVal !== null && xVal !== void 0 ? xVal : 0,
                    y: ((_f = (_e = input.layout) === null || _e === void 0 ? void 0 : _e.yaxis) === null || _f === void 0 ? void 0 : _f.type) === 'date' ? yVal : yVal,
                    value: zVal,
                    rectText: zVal,
                });
                if (typeof zVal === 'number') {
                    zMin = Math.min(zMin, zVal);
                    zMax = Math.max(zMax, zVal);
                }
            });
        });
    }
    var heatmapData = {
        legend: (_j = firstData.name) !== null && _j !== void 0 ? _j : '',
        data: heatmapDataPoints,
        value: 0,
    };
    // Initialize domain and range to default values
    var defaultDomain = [zMin, (zMax + zMin) / 2, zMax];
    var defaultRange = [
        (0, colors_1.getColorFromToken)(colors_1.DataVizPalette.color1),
        (0, colors_1.getColorFromToken)(colors_1.DataVizPalette.color2),
        (0, colors_1.getColorFromToken)(colors_1.DataVizPalette.color3),
    ];
    var colorscale = (_0 = (_u = (_q = (_m = (_k = firstData === null || firstData === void 0 ? void 0 : firstData.colorscale) !== null && _k !== void 0 ? _k : (_l = input.layout) === null || _l === void 0 ? void 0 : _l.colorscale) !== null && _m !== void 0 ? _m : (_p = (_o = input.layout) === null || _o === void 0 ? void 0 : _o.coloraxis) === null || _p === void 0 ? void 0 : _p.colorscale) !== null && _q !== void 0 ? _q : (_t = (_s = (_r = input.layout) === null || _r === void 0 ? void 0 : _r.template) === null || _s === void 0 ? void 0 : _s.layout) === null || _t === void 0 ? void 0 : _t.colorscale) !== null && _u !== void 0 ? _u : (firstData.type === 'histogram2d' && ((_z = (_y = (_x = (_w = (_v = input.layout) === null || _v === void 0 ? void 0 : _v.template) === null || _w === void 0 ? void 0 : _w.data) === null || _x === void 0 ? void 0 : _x.histogram2d) === null || _y === void 0 ? void 0 : _y[0]) === null || _z === void 0 ? void 0 : _z.colorscale))) !== null && _0 !== void 0 ? _0 : (_5 = (_4 = (_3 = (_2 = (_1 = input.layout) === null || _1 === void 0 ? void 0 : _1.template) === null || _2 === void 0 ? void 0 : _2.data) === null || _3 === void 0 ? void 0 : _3.heatmap) === null || _4 === void 0 ? void 0 : _4[0]) === null || _5 === void 0 ? void 0 : _5.colorscale;
    // determine if the types diverging, sequential or sequentialminus are present in colorscale
    if (colorscale &&
        typeof colorscale === 'object' &&
        ('diverging' in colorscale || 'sequential' in colorscale || 'sequentialminus' in colorscale)) {
        var isDivergent = zMin < 0 && zMax > 0; // Data spans both positive and negative values
        var isSequential = zMin >= 0; // Data is entirely positive
        var isSequentialMinus = zMax <= 0; // Data is entirely negative
        if (isDivergent) {
            colorscale = colorscale === null || colorscale === void 0 ? void 0 : colorscale.diverging;
        }
        else if (isSequential) {
            colorscale = colorscale === null || colorscale === void 0 ? void 0 : colorscale.sequential;
        }
        else if (isSequentialMinus) {
            colorscale = colorscale === null || colorscale === void 0 ? void 0 : colorscale.sequentialminus;
        }
    }
    var domainValuesForColorScale = Array.isArray(colorscale)
        ? colorscale.map(function (arr) { return arr[0] * (zMax - zMin) + zMin; })
        : defaultDomain;
    var rangeValuesForColorScale = Array.isArray(colorscale)
        ? colorscale.map(function (arr) { return arr[1]; })
        : defaultRange;
    var _9 = getTitles(input.layout), chartTitle = _9.chartTitle, xAxisTitle = _9.xAxisTitle, yAxisTitle = _9.yAxisTitle;
    return {
        data: [heatmapData],
        domainValuesForColorScale: domainValuesForColorScale,
        rangeValuesForColorScale: rangeValuesForColorScale,
        hideLegend: true,
        showYAxisLables: true,
        chartTitle: chartTitle,
        xAxisTitle: xAxisTitle,
        yAxisTitle: yAxisTitle,
        sortOrder: 'none',
        width: (_6 = input.layout) === null || _6 === void 0 ? void 0 : _6.width,
        height: (_8 = (_7 = input.layout) === null || _7 === void 0 ? void 0 : _7.height) !== null && _8 !== void 0 ? _8 : 350,
        hideTickOverlap: true,
        noOfCharsToTruncate: 20,
        showYAxisLablesTooltip: true,
    };
};
exports.transformPlotlyJsonToHeatmapProps = transformPlotlyJsonToHeatmapProps;
var transformPlotlyJsonToSankeyProps = function (input, colorMap, colorwayType, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
    var _m = input.data[0], link = _m.link, node = _m.node;
    var validLinks = ((_a = link === null || link === void 0 ? void 0 : link.value) !== null && _a !== void 0 ? _a : [])
        .map(function (val, index) {
        var _a, _b;
        if ((0, exports.isInvalidValue)(val) || (0, exports.isInvalidValue)((_a = link === null || link === void 0 ? void 0 : link.source) === null || _a === void 0 ? void 0 : _a[index]) || (0, exports.isInvalidValue)((_b = link === null || link === void 0 ? void 0 : link.target) === null || _b === void 0 ? void 0 : _b[index])) {
            return null;
        }
        return {
            value: val,
            source: link === null || link === void 0 ? void 0 : link.source[index],
            target: link === null || link === void 0 ? void 0 : link.target[index],
        };
    })
        // Filter out negative nodes, unequal nodes and self-references (circular links)
        .filter(function (x) { return x !== null && x.source >= 0 && x.target >= 0 && x.source !== x.target; });
    var extractedNodeColors = (0, PlotlyColorAdapter_1.extractColor)((_d = (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.template) === null || _c === void 0 ? void 0 : _c.layout) === null || _d === void 0 ? void 0 : _d.colorway, colorwayType, node === null || node === void 0 ? void 0 : node.color, colorMap, isDarkTheme);
    var sankeyChartData = {
        nodes: (_e = node.label) === null || _e === void 0 ? void 0 : _e.map(function (label, index) {
            var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedNodeColors, index, label, colorMap, isDarkTheme);
            return {
                nodeId: index,
                name: label,
                color: color,
            };
        }),
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        links: validLinks.map(function (validLink, index) {
            return tslib_1.__assign({}, validLink);
        }),
    };
    var styles = {
        root: tslib_1.__assign({}, (((_g = (_f = input.layout) === null || _f === void 0 ? void 0 : _f.font) === null || _g === void 0 ? void 0 : _g.size) ? { fontSize: (_h = input.layout.font) === null || _h === void 0 ? void 0 : _h.size } : {})),
    };
    var chartTitle = getTitles(input.layout).chartTitle;
    return {
        data: {
            chartTitle: chartTitle,
            SankeyChartData: sankeyChartData,
        },
        width: (_j = input.layout) === null || _j === void 0 ? void 0 : _j.width,
        height: (_l = (_k = input.layout) === null || _k === void 0 ? void 0 : _k.height) !== null && _l !== void 0 ? _l : 468,
        styles: styles,
        enableReflow: true,
    };
};
exports.transformPlotlyJsonToSankeyProps = transformPlotlyJsonToSankeyProps;
var transformPlotlyJsonToGaugeProps = function (input, colorMap, colorwayType, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25;
    var firstData = input.data[0];
    var stepsColors = ((_a = firstData.gauge) === null || _a === void 0 ? void 0 : _a.steps) ? firstData.gauge.steps.map(function (step) { return step.color; }) : undefined;
    var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_d = (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.template) === null || _c === void 0 ? void 0 : _c.layout) === null || _d === void 0 ? void 0 : _d.colorway, colorwayType, stepsColors, colorMap, isDarkTheme);
    var segments = ((_f = (_e = firstData.gauge) === null || _e === void 0 ? void 0 : _e.steps) === null || _f === void 0 ? void 0 : _f.length)
        ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
            firstData.gauge.steps.map(function (step, index) {
                var _a, _b;
                var legend = step.name || "Segment ".concat(index + 1);
                var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, index, legend, colorMap, isDarkTheme);
                return {
                    legend: legend,
                    size: ((_a = step.range) === null || _a === void 0 ? void 0 : _a[1]) - ((_b = step.range) === null || _b === void 0 ? void 0 : _b[0]),
                    color: color,
                };
            })
        : [
            {
                legend: 'Current',
                size: (_g = firstData.value) !== null && _g !== void 0 ? _g : 0 - ((_l = (_k = (_j = (_h = firstData.gauge) === null || _h === void 0 ? void 0 : _h.axis) === null || _j === void 0 ? void 0 : _j.range) === null || _k === void 0 ? void 0 : _k[0]) !== null && _l !== void 0 ? _l : 0),
                color: (0, exports._getGaugeAxisColor)((_p = (_o = (_m = input.layout) === null || _m === void 0 ? void 0 : _m.template) === null || _o === void 0 ? void 0 : _o.layout) === null || _p === void 0 ? void 0 : _p.colorway, colorwayType, (_r = (_q = firstData.gauge) === null || _q === void 0 ? void 0 : _q.axis) === null || _r === void 0 ? void 0 : _r.color, colorMap, isDarkTheme),
            },
            {
                legend: 'Target',
                size: ((_v = (_u = (_t = (_s = firstData.gauge) === null || _s === void 0 ? void 0 : _s.axis) === null || _t === void 0 ? void 0 : _t.range) === null || _u === void 0 ? void 0 : _u[1]) !== null && _v !== void 0 ? _v : 100) - ((_w = firstData.value) !== null && _w !== void 0 ? _w : 0),
                color: colors_1.DataVizPalette.disabled,
            },
        ];
    var sublabel;
    var sublabelColor;
    if ((_x = firstData.delta) === null || _x === void 0 ? void 0 : _x.reference) {
        var diff = firstData.value - firstData.delta.reference;
        if (diff >= 0) {
            sublabel = "\u25B2 ".concat(diff);
            var extractedIncreasingDeltaColors = (0, PlotlyColorAdapter_1.extractColor)((_0 = (_z = (_y = input.layout) === null || _y === void 0 ? void 0 : _y.template) === null || _z === void 0 ? void 0 : _z.layout) === null || _0 === void 0 ? void 0 : _0.colorway, colorwayType, (_2 = (_1 = firstData.delta) === null || _1 === void 0 ? void 0 : _1.increasing) === null || _2 === void 0 ? void 0 : _2.color, colorMap, isDarkTheme);
            var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedIncreasingDeltaColors, 0, '', colorMap, isDarkTheme);
            sublabelColor = color;
        }
        else {
            sublabel = "\u25BC ".concat(Math.abs(diff));
            var extractedDecreasingDeltaColors = (0, PlotlyColorAdapter_1.extractColor)((_5 = (_4 = (_3 = input.layout) === null || _3 === void 0 ? void 0 : _3.template) === null || _4 === void 0 ? void 0 : _4.layout) === null || _5 === void 0 ? void 0 : _5.colorway, colorwayType, (_7 = (_6 = firstData.delta) === null || _6 === void 0 ? void 0 : _6.decreasing) === null || _7 === void 0 ? void 0 : _7.color, colorMap, isDarkTheme);
            var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedDecreasingDeltaColors, 0, '', colorMap, isDarkTheme);
            sublabelColor = color;
        }
    }
    var styles = {
        sublabel: {
            fill: sublabelColor,
        },
    };
    var chartTitle = getTitles(input.layout).chartTitle;
    return {
        segments: segments,
        chartValue: (_8 = firstData.value) !== null && _8 !== void 0 ? _8 : 0,
        chartTitle: chartTitle,
        sublabel: sublabel,
        // range values can be null
        minValue: typeof ((_11 = (_10 = (_9 = firstData.gauge) === null || _9 === void 0 ? void 0 : _9.axis) === null || _10 === void 0 ? void 0 : _10.range) === null || _11 === void 0 ? void 0 : _11[0]) === 'number' ? (_14 = (_13 = (_12 = firstData.gauge) === null || _12 === void 0 ? void 0 : _12.axis) === null || _13 === void 0 ? void 0 : _13.range) === null || _14 === void 0 ? void 0 : _14[0] : undefined,
        maxValue: typeof ((_17 = (_16 = (_15 = firstData.gauge) === null || _15 === void 0 ? void 0 : _15.axis) === null || _16 === void 0 ? void 0 : _16.range) === null || _17 === void 0 ? void 0 : _17[1]) === 'number' ? (_20 = (_19 = (_18 = firstData.gauge) === null || _18 === void 0 ? void 0 : _18.axis) === null || _19 === void 0 ? void 0 : _19.range) === null || _20 === void 0 ? void 0 : _20[1] : undefined,
        chartValueFormat: function () { var _a, _b; return (_b = (_a = firstData.value) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''; },
        width: (_21 = input.layout) === null || _21 === void 0 ? void 0 : _21.width,
        height: (_23 = (_22 = input.layout) === null || _22 === void 0 ? void 0 : _22.height) !== null && _23 !== void 0 ? _23 : 220,
        styles: styles,
        variant: ((_25 = (_24 = firstData.gauge) === null || _24 === void 0 ? void 0 : _24.steps) === null || _25 === void 0 ? void 0 : _25.length) ? index_1.GaugeChartVariant.MultipleSegments : index_1.GaugeChartVariant.SingleSegment,
        roundCorners: true,
    };
};
exports.transformPlotlyJsonToGaugeProps = transformPlotlyJsonToGaugeProps;
var cleanText = function (text) {
    return text
        .replace(/&lt;[^&]*?&gt;/g, '')
        .replace(/<[^>]*>/g, '')
        .replace(/&lt;br&gt;|\\u003cbr\\u003e|<br>/gi, '')
        .replace(/\$[^$]*\$/g, '$')
        .trim();
};
var transformPlotlyJsonToChartTableProps = function (input, colorMap, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    var tableData = input.data[0];
    var normalizeHeaders = function (values) {
        // Case: values is array of arrays
        if (Array.isArray(values[0])) {
            return values.map(function (row) {
                return row
                    .map(function (cell) { return cleanText(cell); })
                    .filter(Boolean)
                    .join(' ');
            });
        }
        // Case: values is 1d array
        return values.map(function (cell) { return cleanText(cell); });
    };
    var columns = (_b = (_a = tableData.cells) === null || _a === void 0 ? void 0 : _a.values) !== null && _b !== void 0 ? _b : [];
    var rows = columns[0].map(function (_, rowIndex) {
        return columns.map(function (col) {
            var cell = col[rowIndex];
            return typeof cell === 'string' ? cleanText(cell) : cell;
        });
    });
    var styles = {
        root: tslib_1.__assign({}, (((_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.font) === null || _d === void 0 ? void 0 : _d.size) ? { fontSize: input.layout.font.size } : {})),
    };
    return {
        headers: normalizeHeaders((_f = (_e = tableData.header) === null || _e === void 0 ? void 0 : _e.values) !== null && _f !== void 0 ? _f : []),
        rows: rows,
        width: (_g = input.layout) === null || _g === void 0 ? void 0 : _g.width,
        height: (_h = input.layout) === null || _h === void 0 ? void 0 : _h.height,
        styles: styles,
    };
};
exports.transformPlotlyJsonToChartTableProps = transformPlotlyJsonToChartTableProps;
var projectPolarToCartesian = function (input) {
    var _a, _b, _c, _d;
    var projection = tslib_1.__assign({}, input);
    for (var sindex = 0; sindex < input.data.length; sindex++) {
        var series = input.data[sindex];
        series.x = [];
        series.y = [];
        for (var ptindex = 0; ptindex < ((_b = (_a = series.r) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0); ptindex++) {
            if ((0, exports.isInvalidValue)((_c = series.theta) === null || _c === void 0 ? void 0 : _c[ptindex]) || (0, exports.isInvalidValue)((_d = series.r) === null || _d === void 0 ? void 0 : _d[ptindex])) {
                continue;
            }
            var thetaRad = (series.theta[ptindex] * Math.PI) / 180;
            var radius = series.r[ptindex];
            series.x.push(radius * Math.cos(thetaRad));
            series.y.push(radius * Math.sin(thetaRad));
        }
        projection.data[sindex] = series;
    }
    return projection;
};
exports.projectPolarToCartesian = projectPolarToCartesian;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isPlainObject(obj) {
    if (window && window.process && window.process.versions) {
        return Object.prototype.toString.call(obj) === '[object Object]';
    }
    return (Object.prototype.toString.call(obj) === '[object Object]' &&
        Object.getPrototypeOf(obj).hasOwnProperty('hasOwnProperty'));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var arrayAttributes = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var stack = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var isArrayStack = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var baseContainer, baseAttrName;
/**
 * Interate iteratively through the trace object and find all the array attributes.
 * 1 trace record = 1 series of data
 * @param trace
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function findArrayAttributes(trace) {
    // Init basecontainer and baseAttrName
    crawlIntoTrace(baseContainer, 0, '');
}
exports.findArrayAttributes = findArrayAttributes;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function crawlIntoTrace(container, i, astrPartial) {
    var item = container[stack[i]];
    var newAstrPartial = astrPartial + stack[i];
    if (i === stack.length - 1) {
        if ((0, chart_utilities_1.isArrayOrTypedArray)(item)) {
            arrayAttributes.push(baseAttrName + newAstrPartial);
        }
    }
    else {
        if (isArrayStack[i]) {
            if (Array.isArray(item)) {
                for (var j = 0; j < item.length; j++) {
                    if (isPlainObject(item[j])) {
                        crawlIntoTrace(item[j], i + 1, newAstrPartial + '[' + j + '].');
                    }
                }
            }
        }
        else if (isPlainObject(item)) {
            crawlIntoTrace(item, i + 1, newAstrPartial + '.');
        }
    }
}
function getLineOptions(line) {
    if (!line) {
        return;
    }
    var lineOptions = {};
    if (line.dash) {
        lineOptions = tslib_1.__assign(tslib_1.__assign({}, lineOptions), dashOptions[line.dash]);
    }
    switch (line.shape) {
        case 'spline':
            var smoothing = typeof line.smoothing === 'number' ? line.smoothing : 1;
            lineOptions.curve = d3_shape_1.curveCardinal.tension(1 - smoothing / 1.3);
            break;
        case 'hv':
            lineOptions.curve = 'stepAfter';
            break;
        case 'vh':
            lineOptions.curve = 'stepBefore';
            break;
        case 'hvh':
            lineOptions.curve = 'step';
            break;
        default:
            lineOptions.curve = 'linear';
    }
    return Object.keys(lineOptions).length > 0 ? lineOptions : undefined;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var isStringArray = function (arr) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return (0, chart_utilities_1.isArrayOfType)(arr, function (value) { return typeof value === 'string' || value === null; });
};
// TODO: Use binary search to find the appropriate bin for numeric value.
var findBinIndex = function (bins, value, isString) {
    if (typeof value === 'undefined' || value === null) {
        return -1;
    }
    return isString
        ? bins.findIndex(function (bin) { return bin.includes(value); })
        : bins.findIndex(function (bin, index) {
            return value >= bin.x0 &&
                (index === bins.length - 1 ? value <= bin.x1 : value < bin.x1);
        });
};
var getBinSize = function (bin) {
    return bin.x1 - bin.x0;
};
var getBinCenter = function (bin) {
    return (bin.x1 + bin.x0) / 2;
};
// TODO: Add support for date axes
var createBins = function (data, binStart, binEnd, binSize) {
    if (!data || data.length === 0) {
        return [];
    }
    if (isStringArray(data)) {
        var categories_1 = Array.from(new Set(data));
        var start = typeof binStart === 'number' ? Math.ceil(binStart) : 0;
        var stop_1 = typeof binEnd === 'number' ? Math.floor(binEnd) + 1 : categories_1.length;
        var step_1 = typeof binSize === 'number' ? binSize : 1;
        return (0, d3_array_1.range)(start, stop_1, step_1).map(function (i) { return categories_1.slice(i, i + step_1); });
    }
    var scale = (0, d3_scale_1.scaleLinear)()
        .domain((0, d3_array_1.extent)(data))
        .nice();
    var _a = scale.domain(), minVal = _a[0], maxVal = _a[1];
    minVal = typeof binStart === 'number' ? binStart : minVal;
    maxVal = typeof binEnd === 'number' ? binEnd : maxVal;
    var binGenerator = (0, d3_array_1.bin)().domain([minVal, maxVal]);
    if (typeof binSize === 'number' && binSize > 0) {
        var thresholds = [];
        var precision = Math.max(getPrecision(minVal), getPrecision(binSize));
        var th = precisionRound(minVal, precision);
        while (th < precisionRound(maxVal + binSize, precision)) {
            thresholds.push(th);
            th = precisionRound(th + binSize, precision);
        }
        minVal = thresholds[0];
        maxVal = thresholds[thresholds.length - 1];
        binGenerator.domain([minVal, maxVal]).thresholds(thresholds);
        // When the domain ends at the last threshold (maxVal), d3Bin creates an extra final bin where
        // both x0 and x1 are equal to maxVal and inclusive. The previous bin also has x1 equal to maxVal,
        // but it is exclusive. To maintain consistent bin widths, remove the final bin,
        // making the previous bin the last one, with both x0 and x1 inclusive.
        return binGenerator(data).slice(0, -1);
    }
    return binGenerator(data);
};
var calculateHistFunc = function (histfunc, bin) {
    var _a, _b;
    switch (histfunc) {
        case 'sum':
            return (0, d3_array_1.sum)(bin);
        case 'avg':
            return bin.length === 0 ? 0 : (0, d3_array_1.sum)(bin) / bin.length;
        case 'min':
            return (_a = (0, d3_array_1.min)(bin)) !== null && _a !== void 0 ? _a : 0;
        case 'max':
            return (_b = (0, d3_array_1.max)(bin)) !== null && _b !== void 0 ? _b : 0;
        default:
            return bin.length;
    }
};
var calculateHistNorm = function (histnorm, value, total, dx, dy) {
    if (dy === void 0) { dy = 1; }
    switch (histnorm) {
        case 'percent':
            return total === 0 ? 0 : (value / total) * 100;
        case 'probability':
            return total === 0 ? 0 : value / total;
        case 'density':
            return dx * dy === 0 ? 0 : value / (dx * dy);
        case 'probability density':
            return total * dx * dy === 0 ? 0 : value / (total * dx * dy);
        default:
            return value;
    }
};
var getPrecision = function (value) {
    var _a, _b;
    return (_b = (_a = value.toString().split('.')[1]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
};
var precisionRound = function (value, precision) {
    var factor = Math.pow(10, precision);
    return Math.round(value * factor) / factor;
};
var getLegendProps = function (data, layout) {
    var legends = [];
    if (data.length === 1) {
        legends.push(data[0].name || '');
    }
    else {
        data.forEach(function (series, index) {
            legends.push(series.name || "Series ".concat(index + 1));
        });
    }
    var hideLegends = data.every(function (series) { return series.showlegend === false; });
    return {
        legends: legends,
        hideLegend: (layout === null || layout === void 0 ? void 0 : layout.showlegend) === false || ((layout === null || layout === void 0 ? void 0 : layout.showlegend) !== true && legends.length < 2) ? true : hideLegends,
    };
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var isInvalidValue = function (value) {
    return typeof value === 'undefined' || value === null || (typeof value === 'number' && !isFinite(value));
};
exports.isInvalidValue = isInvalidValue;
var getNumberAtIndexOrDefault = function (data, index) {
    if ((0, chart_utilities_1.isArrayOrTypedArray)(data)) {
        if (typeof data[index] !== 'number' || !isFinite(data[index])) {
            return;
        }
        return data[index];
    }
    return 1;
};
exports.getNumberAtIndexOrDefault = getNumberAtIndexOrDefault;
var getValidXYRanges = function (series) {
    if (!(0, chart_utilities_1.isArrayOrTypedArray)(series.x) || !(0, chart_utilities_1.isArrayOrTypedArray)(series.y)) {
        return [];
    }
    var ranges = [];
    var start = 0;
    var end = 0;
    for (; end < series.x.length; end++) {
        if ((0, exports.isInvalidValue)(series.x[end]) || (0, exports.isInvalidValue)(series.y[end])) {
            if (end - start > 0) {
                ranges.push([start, end]);
            }
            start = end + 1;
        }
    }
    if (end - start > 0) {
        ranges.push([start, end]);
    }
    return ranges;
};
exports.getValidXYRanges = getValidXYRanges;
//# sourceMappingURL=PlotlySchemaAdapter.js.map