"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findArrayAttributes = exports.isArrayOrTypedArray = exports.sanitizeJson = exports.transformPlotlyJsonToGaugeProps = exports.transformPlotlyJsonToSankeyProps = exports.transformPlotlyJsonToHeatmapProps = exports.transformPlotlyJsonToHorizontalBarWithAxisProps = exports.transformPlotlyJsonToScatterChartProps = exports.transformPlotlyJsonToVBCProps = exports.transformPlotlyJsonToGVBCProps = exports.transformPlotlyJsonToVSBCProps = exports.transformPlotlyJsonToDonutProps = exports.getColor = exports.updateXValues = exports.isLineData = exports.isMonthArray = exports.isNumberArray = exports.isDateArray = void 0;
var tslib_1 = require("tslib");
var d3_array_1 = require("d3-array");
var d3_scale_1 = require("d3-scale");
var d3_format_1 = require("d3-format");
var colors_1 = require("../../utilities/colors");
var index_1 = require("../GaugeChart/index");
var utilities_1 = require("../../utilities/utilities");
var d3_time_format_1 = require("d3-time-format");
var SUPPORTED_PLOT_TYPES = ['pie', 'bar', 'scatter', 'heatmap', 'sankey', 'indicator', 'histogram'];
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',
    },
};
var isDate = function (value) {
    var parsedDate = new Date(Date.parse(value));
    if (isNaN(parsedDate.getTime())) {
        return false;
    }
    var parsedYear = parsedDate.getFullYear();
    var yearInString = /\b\d{4}\b/.test(value);
    if (!yearInString && (parsedYear === 2000 || parsedYear === 2001)) {
        return false;
    }
    return true;
};
var isNumber = function (value) { return !isNaN(parseFloat(value)) && isFinite(value); };
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 isArrayOfType = function (plotCoordinates, typeCheck) {
    var args = [];
    for (var _i = 2; _i < arguments.length; _i++) {
        args[_i - 2] = arguments[_i];
    }
    if (!isArrayOrTypedArray(plotCoordinates)) {
        return false;
    }
    if (plotCoordinates.length === 0) {
        return false;
    }
    if (Array.isArray(plotCoordinates[0])) {
        // Handle 2D array
        return plotCoordinates.every(function (innerArray) { return innerArray.every(function (datum) { return typeCheck.apply(void 0, tslib_1.__spreadArray([datum], args, false)); }); });
    }
    else {
        // Handle 1D array
        return plotCoordinates.every(function (datum) { return typeCheck.apply(void 0, tslib_1.__spreadArray([datum], args, false)); });
    }
};
var isDateArray = function (data) {
    return isArrayOfType(data, isDate);
};
exports.isDateArray = isDateArray;
var isNumberArray = function (data) {
    return isArrayOfType(data, isNumber);
};
exports.isNumberArray = isNumberArray;
var isMonthArray = function (data) {
    return isArrayOfType(data, isMonth);
};
exports.isMonthArray = isMonthArray;
var isLineData = function (data) {
    return (!SUPPORTED_PLOT_TYPES.includes("".concat(data.type)) &&
        Array.isArray(data.x) &&
        isArrayOfType(data.y, function (value) { return typeof value === 'number'; }) &&
        data.x.length > 0 &&
        data.x.length === data.y.length);
};
exports.isLineData = isLineData;
var invalidate2Dseries = function (series, chartType) {
    var _a, _b;
    if (((_a = series.x) === null || _a === void 0 ? void 0 : _a.length) > 0 && Array.isArray(series.x[0])) {
        throw new Error("transform to ".concat(chartType, ":: 2D x array not supported"));
    }
    if (((_b = series.y) === null || _b === void 0 ? void 0 : _b.length) > 0 && Array.isArray(series.y[0])) {
        throw new Error("transform to ".concat(chartType, ":: 2D y array not supported"));
    }
};
var getLegend = function (series, index) {
    return series.name || "Series ".concat(index + 1);
};
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;
}
var updateXValues = 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 isDate(parsedDate) ? new Date(parsedDate) : null;
    });
    for (var i = dates.length - 1; i > 0; i--) {
        var currentMonth = dates[i].getMonth();
        var previousMonth = dates[i - 1].getMonth();
        var currentYear = dates[i].getFullYear();
        var previousYear = dates[i - 1].getFullYear();
        if (previousMonth >= currentMonth) {
            dates[i - 1].setFullYear(dates[i].getFullYear() - 1);
        }
        else if (previousYear > currentYear) {
            dates[i - 1].setFullYear(currentYear);
        }
    }
    xValues = xValues.map(function (month, index) {
        return "".concat(month, " 01, ").concat(dates[index].getFullYear());
    });
    return xValues;
};
exports.updateXValues = updateXValues;
var getColor = function (legendLabel, colorMap, isDarkTheme) {
    if (!colorMap.current.has(legendLabel)) {
        var nextColor = (0, colors_1.getNextColor)(colorMap.current.size + 1, 0, isDarkTheme);
        colorMap.current.set(legendLabel, nextColor);
        return nextColor;
    }
    return colorMap.current.get(legendLabel);
};
exports.getColor = getColor;
var getSecondaryYAxisValues = function (series, layout) {
    var _a;
    var secondaryYAxisValues = {};
    if (layout && layout.yaxis2 && series.yaxis === 'y2') {
        secondaryYAxisValues.secondaryYAxistitle =
            typeof layout.yaxis2.title === 'string'
                ? layout.yaxis2.title
                : typeof ((_a = layout.yaxis2.title) === null || _a === void 0 ? void 0 : _a.text) === 'string'
                    ? layout.yaxis2.title.text
                    : '';
        if (layout.yaxis2.range) {
            secondaryYAxisValues.secondaryYScaleOptions = {
                yMinValue: layout.yaxis2.range[0],
                yMaxValue: layout.yaxis2.range[1],
            };
        }
        else {
            var yValues = series.y;
            if (yValues) {
                secondaryYAxisValues.secondaryYScaleOptions = {
                    yMinValue: Math.min.apply(Math, yValues),
                    yMaxValue: Math.max.apply(Math, yValues),
                };
            }
        }
    }
    secondaryYAxisValues.secondaryYAxistitle =
        secondaryYAxisValues.secondaryYAxistitle !== '' ? secondaryYAxisValues.secondaryYAxistitle : undefined;
    secondaryYAxisValues.secondaryYScaleOptions =
        secondaryYAxisValues.secondaryYScaleOptions && Object.keys(secondaryYAxisValues.secondaryYScaleOptions).length !== 0
            ? secondaryYAxisValues.secondaryYScaleOptions
            : undefined;
    return secondaryYAxisValues;
};
var transformPlotlyJsonToDonutProps = function (input, colorMap, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f, _g;
    var firstData = input.data[0];
    var donutData = (_a = firstData.labels) === null || _a === void 0 ? void 0 : _a.map(function (label, index) {
        var _a;
        var color = (0, exports.getColor)(label, colorMap, isDarkTheme);
        return {
            legend: label,
            data: (_a = firstData.values) === null || _a === void 0 ? void 0 : _a[index], //ToDo how to handle string data?
            color: color,
        };
    });
    var width = (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.width) !== null && _c !== void 0 ? _c : 440;
    var height = (_e = (_d = input.layout) === null || _d === void 0 ? void 0 : _d.height) !== null && _e !== void 0 ? _e : 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: donutData,
        },
        hideLegend: ((_f = input.layout) === null || _f === void 0 ? void 0 : _f.showlegend) === false ? true : false,
        width: (_g = input.layout) === null || _g === void 0 ? void 0 : _g.width,
        height: height,
        innerRadius: innerRadius,
        hideLabels: hideLabels,
        showLabelsInPercent: firstData.textinfo ? ['percent', 'label+percent'].includes(firstData.textinfo) : true,
    };
};
exports.transformPlotlyJsonToDonutProps = transformPlotlyJsonToDonutProps;
var transformPlotlyJsonToVSBCProps = function (input, colorMap, isDarkTheme, fallbackVSBC) {
    var _a, _b, _c;
    var mapXToDataPoints = {};
    var yMaxValue = 0;
    var secondaryYAxisValues = {};
    input.data.forEach(function (series, index1) {
        var _a;
        invalidate2Dseries(series, 'VSBC');
        if (!(0, exports.isNumberArray)(series.y)) {
            throw new Error('transform to VSBC:: y values should be numeric');
        }
        (_a = series.x) === null || _a === void 0 ? void 0 : _a.forEach(function (x, index2) {
            var _a, _b, _c;
            if (!mapXToDataPoints[x]) {
                mapXToDataPoints[x] = { xAxisPoint: x, chartData: [], lineData: [] };
            }
            var legend = getLegend(series, index1);
            var yVal = (_b = (_a = series.y) === null || _a === void 0 ? void 0 : _a[index2]) !== null && _b !== void 0 ? _b : 0;
            if (series.type === 'bar') {
                var color = (0, exports.getColor)(legend, colorMap, isDarkTheme);
                mapXToDataPoints[x].chartData.push({
                    legend: legend,
                    data: yVal,
                    color: color,
                });
            }
            else if (series.type === 'scatter' || (0, exports.isLineData)(series) || !!fallbackVSBC) {
                var color = (0, exports.getColor)(legend, colorMap, isDarkTheme);
                mapXToDataPoints[x].lineData.push(tslib_1.__assign(tslib_1.__assign({ legend: legend }, (((_c = series.line) === null || _c === void 0 ? void 0 : _c.dash) && dashOptions[series.line.dash]
                    ? { lineOptions: tslib_1.__assign({}, dashOptions[series.line.dash]) }
                    : {})), { y: yVal, color: color }));
            }
            yMaxValue = Math.max(yMaxValue, yVal);
        });
        secondaryYAxisValues = getSecondaryYAxisValues(series, input.layout);
    });
    var _d = getTitles(input.layout), chartTitle = _d.chartTitle, xAxisTitle = _d.xAxisTitle, yAxisTitle = _d.yAxisTitle;
    return {
        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,
        chartTitle: chartTitle,
        xAxisTitle: xAxisTitle,
        yAxisTitle: yAxisTitle,
        mode: 'plotly',
        secondaryYAxistitle: secondaryYAxisValues.secondaryYAxistitle,
        secondaryYScaleOptions: secondaryYAxisValues.secondaryYScaleOptions,
        hideTickOverlap: true,
    };
};
exports.transformPlotlyJsonToVSBCProps = transformPlotlyJsonToVSBCProps;
var transformPlotlyJsonToGVBCProps = function (input, colorMap, isDarkTheme) {
    var _a, _b, _c;
    var mapXToDataPoints = {};
    var secondaryYAxisValues = {};
    input.data.forEach(function (series, index1) {
        var _a;
        invalidate2Dseries(series, 'GVBC');
        if (!(0, exports.isNumberArray)(series.y)) {
            throw new Error('transform to GVBC:: y values should be numeric');
        }
        (_a = series.x) === null || _a === void 0 ? void 0 : _a.forEach(function (x, index2) {
            var _a, _b;
            if (!mapXToDataPoints[x]) {
                mapXToDataPoints[x] = { name: x.toString(), series: [] };
            }
            if (series.type === 'bar') {
                var legend = getLegend(series, index1);
                var color = (0, exports.getColor)(legend, colorMap, isDarkTheme);
                mapXToDataPoints[x].series.push({
                    key: legend,
                    data: (_b = (_a = series.y) === null || _a === void 0 ? void 0 : _a[index2]) !== null && _b !== void 0 ? _b : 0,
                    xAxisCalloutData: x,
                    color: color,
                    legend: legend,
                });
            }
        });
        secondaryYAxisValues = getSecondaryYAxisValues(series, input.layout);
    });
    var _d = getTitles(input.layout), chartTitle = _d.chartTitle, xAxisTitle = _d.xAxisTitle, yAxisTitle = _d.yAxisTitle;
    return {
        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',
        secondaryYAxistitle: secondaryYAxisValues.secondaryYAxistitle,
        secondaryYScaleOptions: secondaryYAxisValues.secondaryYScaleOptions,
        hideTickOverlap: true,
    };
};
exports.transformPlotlyJsonToGVBCProps = transformPlotlyJsonToGVBCProps;
var transformPlotlyJsonToVBCProps = function (input, colorMap, isDarkTheme) {
    var _a, _b, _c;
    var vbcData = [];
    input.data.forEach(function (series, index) {
        var _a, _b, _c;
        invalidate2Dseries(series, 'VBC');
        if (!series.x) {
            return;
        }
        var scale = (0, d3_scale_1.scaleLinear)()
            .domain((0, d3_array_1.extent)(series.x))
            .nice();
        var _d = scale.domain(), xMin = _d[0], xMax = _d[1];
        xMin = typeof ((_a = series.xbins) === null || _a === void 0 ? void 0 : _a.start) === 'number' ? series.xbins.start : xMin;
        xMax = typeof ((_b = series.xbins) === null || _b === void 0 ? void 0 : _b.end) === 'number' ? series.xbins.end : xMax;
        var bin = (0, d3_array_1.bin)().domain([xMin, xMax]);
        if (typeof ((_c = series.xbins) === null || _c === void 0 ? void 0 : _c.size) === 'number') {
            var thresholds = [];
            var th = xMin;
            var precision = (0, d3_format_1.precisionFixed)(series.xbins.size);
            var format = (0, d3_format_1.format)(".".concat(precision, "f"));
            while (th < xMax + series.xbins.size) {
                thresholds.push(parseFloat(format(th)));
                th += series.xbins.size;
            }
            xMin = thresholds[0];
            xMax = thresholds[thresholds.length - 1];
            bin.domain([xMin, xMax]).thresholds(thresholds);
        }
        var buckets = bin(series.x);
        // If the start or end of xbins is specified, then the number of datapoints may become less than x.length
        var totalDataPoints = (0, d3_array_1.merge)(buckets).length;
        buckets.forEach(function (bucket) {
            var legend = getLegend(series, index);
            var color = (0, exports.getColor)(legend, colorMap, isDarkTheme);
            var y = bucket.length;
            if (series.histnorm === 'percent') {
                y = (bucket.length / totalDataPoints) * 100;
            }
            else if (series.histnorm === 'probability') {
                y = bucket.length / totalDataPoints;
            }
            else if (series.histnorm === 'density') {
                y = bucket.x0 === bucket.x1 ? 0 : bucket.length / (bucket.x1 - bucket.x0);
            }
            else if (series.histnorm === 'probability density') {
                y = bucket.x0 === bucket.x1 ? 0 : bucket.length / (totalDataPoints * (bucket.x1 - bucket.x0));
            }
            else if (series.histfunc === 'sum') {
                y = (0, d3_array_1.sum)(bucket);
            }
            else if (series.histfunc === 'avg') {
                y = bucket.length === 0 ? 0 : (0, d3_array_1.sum)(bucket) / bucket.length;
            }
            else if (series.histfunc === 'min') {
                y = (0, d3_array_1.min)(bucket);
            }
            else if (series.histfunc === 'max') {
                y = (0, d3_array_1.max)(bucket);
            }
            vbcData.push({
                x: (bucket.x1 + bucket.x0) / 2,
                y: y,
                legend: legend,
                color: color,
                xAxisCalloutData: "[".concat(bucket.x0, " - ").concat(bucket.x1, ")"),
            });
        });
    });
    var _d = getTitles(input.layout), chartTitle = _d.chartTitle, xAxisTitle = _d.xAxisTitle, yAxisTitle = _d.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: 'plotly',
        hideTickOverlap: true,
    };
};
exports.transformPlotlyJsonToVBCProps = transformPlotlyJsonToVBCProps;
var transformPlotlyJsonToScatterChartProps = function (input, isAreaChart, colorMap, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f;
    var secondaryYAxisValues = {};
    var mode = 'tonexty';
    var chartData = input.data.map(function (series, index) {
        var _a;
        invalidate2Dseries(series, 'Scatter');
        var xValues = series.x;
        var isString = typeof xValues[0] === 'string';
        var isXDate = (0, exports.isDateArray)(xValues);
        var isXNumber = (0, exports.isNumberArray)(xValues);
        var legend = getLegend(series, index);
        var lineColor = (0, exports.getColor)(legend, colorMap, isDarkTheme);
        secondaryYAxisValues = getSecondaryYAxisValues(series, input.layout);
        mode = series.fill === 'tozeroy' ? 'tozeroy' : 'tonexty';
        return tslib_1.__assign(tslib_1.__assign({ legend: legend }, (((_a = series.line) === null || _a === void 0 ? void 0 : _a.dash) && dashOptions[series.line.dash]
            ? { lineOptions: tslib_1.__assign({}, dashOptions[series.line.dash]) }
            : {})), { data: xValues.map(function (x, i) {
                var _a, _b;
                return (tslib_1.__assign({ x: isString ? (isXDate ? new Date(x) : isXNumber ? parseFloat(x) : x) : x, y: series.y[i] }, (Array.isArray((_a = series.marker) === null || _a === void 0 ? void 0 : _a.size)
                    ? { markerSize: series.marker.size[i] }
                    : typeof ((_b = series.marker) === null || _b === void 0 ? void 0 : _b.size) === 'number'
                        ? { markerSize: series.marker.size }
                        : {})));
            }), color: lineColor });
    });
    var yMinMaxValues = (0, utilities_1.findNumericMinMaxOfY)(chartData);
    var _g = getTitles(input.layout), chartTitle = _g.chartTitle, xAxisTitle = _g.xAxisTitle, yAxisTitle = _g.yAxisTitle;
    var chartProps = {
        chartTitle: chartTitle,
        lineChartData: chartData,
    };
    if (isAreaChart) {
        return {
            data: chartProps,
            supportNegativeData: true,
            xAxisTitle: xAxisTitle,
            yAxisTitle: yAxisTitle,
            secondaryYAxistitle: secondaryYAxisValues.secondaryYAxistitle,
            secondaryYScaleOptions: secondaryYAxisValues.secondaryYScaleOptions,
            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,
        };
    }
    else {
        return {
            data: chartProps,
            supportNegativeData: true,
            xAxisTitle: xAxisTitle,
            yAxisTitle: yAxisTitle,
            secondaryYAxistitle: secondaryYAxisValues.secondaryYAxistitle,
            secondaryYScaleOptions: secondaryYAxisValues.secondaryYScaleOptions,
            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,
        };
    }
};
exports.transformPlotlyJsonToScatterChartProps = transformPlotlyJsonToScatterChartProps;
var transformPlotlyJsonToHorizontalBarWithAxisProps = function (input, colorMap, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
    var chartData = input.data
        .map(function (series, index) {
        invalidate2Dseries(series, 'HBC');
        return series.y.map(function (yValue, i) {
            var color = (0, exports.getColor)(yValue, colorMap, isDarkTheme);
            return {
                x: series.x[i],
                y: yValue,
                legend: yValue,
                color: color,
            };
        });
    })
        .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 numberOfBars = input.data[0].y.length;
    var scalingFactor = 0.01;
    var gapFactor = 1 / (1 + scalingFactor * numberOfBars);
    var barHeight = availableHeight / (numberOfBars * (1 + gapFactor));
    var _s = getTitles(input.layout), chartTitle = _s.chartTitle, xAxisTitle = _s.xAxisTitle, yAxisTitle = _s.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,
    };
};
exports.transformPlotlyJsonToHorizontalBarWithAxisProps = transformPlotlyJsonToHorizontalBarWithAxisProps;
var transformPlotlyJsonToHeatmapProps = function (input) {
    var _a, _b, _c, _d;
    var firstData = input.data[0];
    var heatmapDataPoints = [];
    var zMin = Number.POSITIVE_INFINITY;
    var zMax = Number.NEGATIVE_INFINITY;
    (_a = firstData.x) === null || _a === void 0 ? void 0 : _a.forEach(function (xVal, xIdx) {
        var _a;
        (_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: firstData.name,
        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 domainValuesForColorScale = Array.isArray(firstData.colorscale)
        ? firstData.colorscale.map(function (arr) { return arr[0] * (zMax - zMin) + zMin; })
        : defaultDomain;
    var rangeValuesForColorScale = Array.isArray(firstData.colorscale)
        ? firstData.colorscale.map(function (arr) { return arr[1]; })
        : defaultRange;
    var _e = getTitles(input.layout), chartTitle = _e.chartTitle, xAxisTitle = _e.xAxisTitle, yAxisTitle = _e.yAxisTitle;
    return {
        data: [heatmapData],
        domainValuesForColorScale: domainValuesForColorScale,
        rangeValuesForColorScale: rangeValuesForColorScale,
        hideLegend: true,
        showYAxisLables: true,
        chartTitle: chartTitle,
        xAxisTitle: xAxisTitle,
        yAxisTitle: yAxisTitle,
        sortOrder: 'none',
        width: (_b = input.layout) === null || _b === void 0 ? void 0 : _b.width,
        height: (_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.height) !== null && _d !== void 0 ? _d : 350,
        hideTickOverlap: true,
    };
};
exports.transformPlotlyJsonToHeatmapProps = transformPlotlyJsonToHeatmapProps;
var transformPlotlyJsonToSankeyProps = function (input, colorMap, isDarkTheme) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    var _j = input.data[0], link = _j.link, node = _j.node;
    var validLinks = ((_a = link === null || link === void 0 ? void 0 : link.value) !== null && _a !== void 0 ? _a : [])
        .map(function (val, index) { 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],
    }); })
        // eslint-disable-next-line @typescript-eslint/no-shadow
        // Filter out negative nodes, unequal nodes and self-references (circular links)
        .filter(function (x) { return x.source >= 0 && x.target >= 0 && x.source !== x.target; });
    var sankeyChartData = {
        nodes: (_b = node.label) === null || _b === void 0 ? void 0 : _b.map(function (label, index) {
            var color = (0, exports.getColor)(label, colorMap, isDarkTheme);
            return {
                nodeId: index,
                name: label,
                color: color,
            };
        }),
        links: validLinks.map(function (validLink, index) {
            return tslib_1.__assign({}, validLink);
        }),
    };
    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: (_e = input.layout.font) === null || _e === void 0 ? void 0 : _e.size } : {})),
    };
    var chartTitle = getTitles(input.layout).chartTitle;
    return {
        data: {
            chartTitle: chartTitle,
            SankeyChartData: sankeyChartData,
        },
        width: (_f = input.layout) === null || _f === void 0 ? void 0 : _f.width,
        height: (_h = (_g = input.layout) === null || _g === void 0 ? void 0 : _g.height) !== null && _h !== void 0 ? _h : 468,
        styles: styles,
        enableReflow: true,
    };
};
exports.transformPlotlyJsonToSankeyProps = transformPlotlyJsonToSankeyProps;
var transformPlotlyJsonToGaugeProps = function (input, colorMap, 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;
    var firstData = input.data[0];
    var segments = ((_b = (_a = firstData.gauge) === null || _a === void 0 ? void 0 : _a.steps) === null || _b === void 0 ? void 0 : _b.length)
        ? firstData.gauge.steps.map(function (step, index) {
            var _a, _b;
            var legend = step.name || "Segment ".concat(index + 1);
            var color = (0, exports.getColor)(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: (_c = firstData.value) !== null && _c !== void 0 ? _c : 0 - ((_g = (_f = (_e = (_d = firstData.gauge) === null || _d === void 0 ? void 0 : _d.axis) === null || _e === void 0 ? void 0 : _e.range) === null || _f === void 0 ? void 0 : _f[0]) !== null && _g !== void 0 ? _g : 0),
                color: (0, exports.getColor)('Current', colorMap, isDarkTheme),
            },
            {
                legend: 'Target',
                size: ((_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[1]) !== null && _l !== void 0 ? _l : 100) - ((_m = firstData.value) !== null && _m !== void 0 ? _m : 0),
                color: colors_1.DataVizPalette.disabled,
            },
        ];
    var sublabel;
    var sublabelColor;
    if ((_o = firstData.delta) === null || _o === void 0 ? void 0 : _o.reference) {
        var diff = firstData.value - firstData.delta.reference;
        if (diff >= 0) {
            sublabel = "\u25B2 ".concat(diff);
            var color = (0, colors_1.getColorFromToken)(colors_1.DataVizPalette.success, isDarkTheme);
            sublabelColor = color;
        }
        else {
            sublabel = "\u25BC ".concat(Math.abs(diff));
            var color = (0, colors_1.getColorFromToken)(colors_1.DataVizPalette.error, isDarkTheme);
            sublabelColor = color;
        }
    }
    var styles = {
        sublabel: {
            fill: sublabelColor,
        },
    };
    var chartTitle = getTitles(input.layout).chartTitle;
    return {
        segments: segments,
        chartValue: (_p = firstData.value) !== null && _p !== void 0 ? _p : 0,
        chartTitle: chartTitle,
        sublabel: sublabel,
        // range values can be null
        minValue: typeof ((_s = (_r = (_q = firstData.gauge) === null || _q === void 0 ? void 0 : _q.axis) === null || _r === void 0 ? void 0 : _r.range) === null || _s === void 0 ? void 0 : _s[0]) === 'number' ? (_v = (_u = (_t = firstData.gauge) === null || _t === void 0 ? void 0 : _t.axis) === null || _u === void 0 ? void 0 : _u.range) === null || _v === void 0 ? void 0 : _v[0] : undefined,
        maxValue: typeof ((_y = (_x = (_w = firstData.gauge) === null || _w === void 0 ? void 0 : _w.axis) === null || _x === void 0 ? void 0 : _x.range) === null || _y === void 0 ? void 0 : _y[1]) === 'number' ? (_1 = (_0 = (_z = firstData.gauge) === null || _z === void 0 ? void 0 : _z.axis) === null || _0 === void 0 ? void 0 : _0.range) === null || _1 === void 0 ? void 0 : _1[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: (_2 = input.layout) === null || _2 === void 0 ? void 0 : _2.width,
        height: (_4 = (_3 = input.layout) === null || _3 === void 0 ? void 0 : _3.height) !== null && _4 !== void 0 ? _4 : 220,
        styles: styles,
        variant: ((_6 = (_5 = firstData.gauge) === null || _5 === void 0 ? void 0 : _5.steps) === null || _6 === void 0 ? void 0 : _6.length) ? index_1.GaugeChartVariant.MultipleSegments : index_1.GaugeChartVariant.SingleSegment,
    };
};
exports.transformPlotlyJsonToGaugeProps = transformPlotlyJsonToGaugeProps;
var MAX_DEPTH = 15;
var sanitizeJson = function (jsonObject, depth) {
    if (depth === void 0) { depth = 0; }
    if (depth > MAX_DEPTH) {
        throw new Error('Maximum json depth exceeded');
    }
    if (typeof jsonObject === 'object' && jsonObject !== null) {
        for (var key in jsonObject) {
            if (jsonObject.hasOwnProperty(key)) {
                if (typeof jsonObject[key] === 'string') {
                    jsonObject[key] = jsonObject[key].replace(/</g, '&lt;').replace(/>/g, '&gt;');
                }
                else {
                    jsonObject[key] = (0, exports.sanitizeJson)(jsonObject[key], depth + 1);
                }
            }
        }
    }
    return jsonObject;
};
exports.sanitizeJson = sanitizeJson;
function isTypedArray(a) {
    return ArrayBuffer.isView(a) && !(a instanceof DataView);
}
function isArrayOrTypedArray(a) {
    return Array.isArray(a) || isTypedArray(a);
}
exports.isArrayOrTypedArray = isArrayOrTypedArray;
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'));
}
var arrayAttributes = [];
var stack = [];
var isArrayStack = [];
var baseContainer, baseAttrName;
/**
 * Interate iteratively through the trace object and find all the array attributes.
 * 1 trace record = 1 series of data
 * @param trace
 */
function findArrayAttributes(trace) {
    // Init basecontainer and baseAttrName
    crawlIntoTrace(baseContainer, 0, '');
}
exports.findArrayAttributes = findArrayAttributes;
function crawlIntoTrace(container, i, astrPartial) {
    var item = container[stack[i]];
    var newAstrPartial = astrPartial + stack[i];
    if (i === stack.length - 1) {
        if (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 + '.');
        }
    }
}
//# sourceMappingURL=PlotlySchemaAdapter.js.map