"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HlcDataSeries = void 0;
var Deleter_1 = require("../../Core/Deleter");
var Guard_1 = require("../../Core/Guard");
var NumberRange_1 = require("../../Core/NumberRange");
var SearchMode_1 = require("../../types/SearchMode");
var ValueName_1 = require("../../types/ValueName");
var YRangeMode_1 = require("../../types/YRangeMode");
var isRealNumber_1 = require("../../utils/isRealNumber");
var vectorToArray_1 = require("../../utils/vectorToArray");
var BaseDataSeries_1 = require("./BaseDataSeries");
var IDataSeries_1 = require("./IDataSeries");
/**
 * HlcDataSeries is a DataSeries for holding X, Y, H, L data in SciChart's 2D
 * {@link https://www.scichart.com/javascript-chart-features | JavaScript Charts}
 * @remarks
 * The HlcDataSeries is primarily used with our {@link FastErrorBarsRenderableSeries | JavaScript Error Bars Chart},
 * which draws a High-Low Bars around points
 *
 * A DataSeries stores the data to render. This is independent from the {@link IRenderableSeries | RenderableSeries}
 * which defines how that data should be rendered.
 *
 * See derived types of {@link BaseDataSeries} to find out what data-series are available.
 * See derived types of {@link IRenderableSeries} to find out what 2D JavaScript Chart types are available.
 *
 * ---
 * 📚 Docs: {@link https://www.scichart.com/documentation/js/v4/2d-charts/chart-types/data-series-api/data-series-api-overview/}
 */
var HlcDataSeries = /** @class */ (function (_super) {
    __extends(HlcDataSeries, _super);
    /**
     * Creates an instance of {@link HlcDataSeries}
     * @param webAssemblyContext the {@link TSciChart | SciChart WebAssembly Context} containing native methods
     * and access to our underlying WebGL2 rendering engine
     * @param options the {@link IHlcDataSeriesOptions} which can be passed to configure the DataSeries at construct time
     *
     * ---
     * 📚 Docs: {@link https://www.scichart.com/documentation/js/v4/2d-charts/chart-types/data-series-api/data-series-api-overview/}
     */
    function HlcDataSeries(webAssemblyContext, options) {
        var _this = _super.call(this, webAssemblyContext, __assign(__assign({}, options), { arrayCount: 3, valueNames: [ValueName_1.EValueName.Close, ValueName_1.EValueName.High, ValueName_1.EValueName.Low], includeInYRange: [true, true, true] })) || this;
        /** @inheritDoc */
        _this.type = IDataSeries_1.EDataSeriesType.Hlc;
        if (options === null || options === void 0 ? void 0 : options.xValues) {
            Guard_1.Guard.notNull(options.yValues, "options.yValues");
            Guard_1.Guard.notNull(options.highValues, "options.highValues");
            Guard_1.Guard.notNull(options.lowValues, "options.lowValues");
            _this.appendRange(options.xValues, options.yValues, options.highValues, options.lowValues, options.metadata);
            if ((options === null || options === void 0 ? void 0 : options.fifoCapacity) && (options === null || options === void 0 ? void 0 : options.fifoStartIndex)) {
                _this.xValues.notifyAppend(options === null || options === void 0 ? void 0 : options.fifoStartIndex);
                _this.yValues.notifyAppend(options === null || options === void 0 ? void 0 : options.fifoStartIndex);
                _this.highValues.notifyAppend(options === null || options === void 0 ? void 0 : options.fifoStartIndex);
                _this.lowValues.notifyAppend(options === null || options === void 0 ? void 0 : options.fifoStartIndex);
            }
        }
        return _this;
    }
    Object.defineProperty(HlcDataSeries.prototype, "yValues", {
        get: function () {
            return this.getNativeYValues();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(HlcDataSeries.prototype, "highValues", {
        get: function () {
            return this.getNativeYValues(1);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(HlcDataSeries.prototype, "lowValues", {
        get: function () {
            return this.getNativeYValues(2);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Gets a native / WebAssembly vector of H-values in the DataSeries
     */
    HlcDataSeries.prototype.getNativeHighValues = function () {
        return this.highValues;
    };
    /**
     * Gets a native / WebAssembly vector of L-values in the DataSeries
     */
    HlcDataSeries.prototype.getNativeLowValues = function () {
        return this.lowValues;
    };
    /**
     * Appends a single X, Y, Y1 point to the DataSeries
     * @remarks
     * For best performance on drawing large datasets, use the {@link appendRange} method
     *
     * Any changes of the DataSeries will trigger a redraw on the parent {@link SciChartSurface}
     * @param x The X-value
     * @param y The Y1-value
     * @param h The H-value
     * @param l The L-value
     * @param metadata The point metadata
     */
    HlcDataSeries.prototype.append = function (x, y, h, l, metadata) {
        _super.prototype.appendN.call(this, x, [y, h, l], metadata);
    };
    /**
     * Appends a range of X, Y, Y1 points to the DataSeries
     * @remarks
     * This method is considerably higher performance than {@link append} which appends a single point
     *
     * Any changes of the DataSeries will trigger a redraw on the parent {@link SciChartSurface}
     * @param xValues The X-values
     * @param yValues The Y-values
     * @param y1Values The Y1-values
     * @param metadata The array of point metadata
     */
    HlcDataSeries.prototype.appendRange = function (xValues, yValues, hValues, lValues, metadata) {
        _super.prototype.appendRangeN.call(this, xValues, [yValues, hValues, lValues], metadata);
    };
    /**
     * Updates a single Y, H, L-value by X-index
     * @remarks Any changes of the DataSeries will trigger a redraw on the parent {@link SciChartSurface}
     * @param index the index to update
     * @param y The new Y value
     * @param h The new H value
     * @param l The new L value
     * @param metadata The point metadata
     */
    HlcDataSeries.prototype.update = function (index, y, h, l, metadata) {
        _super.prototype.updateN.call(this, index, [y, h, l], metadata);
    };
    /**
     * Updates a single X, Y, H, L-value by X-index. Might also need to set isSorted = false
     * @remarks Any changes of the DataSeries will trigger a redraw on the parent {@link SciChartSurface}
     * @param index the index to update
     * @param x The new X value
     * @param y The new Y value
     * @param h The new H value
     * @param l The new L value
     * @param metadata The point metadata
     */
    HlcDataSeries.prototype.updateXyhl = function (index, x, y, h, l, metadata) {
        _super.prototype.updateXyN.call(this, index, x, [y, h, l], metadata);
    };
    /**
     * Inserts a single X,Y, H, L value at the start index
     * @remarks
     * For best performance on drawing large datasets, use the {@link insertRange} method
     *
     * Any changes of the DataSeries will trigger a redraw on the parent {@link SciChartSurface}
     * @param startIndex the index to insert at
     * @param x the XValue
     * @param y the YValue
     * @param h the HighValue
     * @param l the LowValue
     * @param metadata The point metadata
     */
    HlcDataSeries.prototype.insert = function (startIndex, x, y, h, l, metadata) {
        _super.prototype.insertN.call(this, startIndex, x, [y, h, l], metadata);
    };
    /**
     * Inserts a range of X,Y, H, L values at the startIndex
     * @remarks
     * Any changes of the DataSeries will trigger a redraw on the parent {@link SciChartSurface}
     * @param startIndex the index to insert at
     * @param xValues the XValues
     * @param yValues the YValues
     * @param hValues the HValues
     * @param lValues the LValues
     * @param metadata The array of point metadata
     */
    HlcDataSeries.prototype.insertRange = function (startIndex, xValues, yValues, hValues, lValues, metadata) {
        _super.prototype.insertRangeN.call(this, startIndex, xValues, [yValues, hValues, lValues], metadata);
    };
    /** @inheritDoc */
    HlcDataSeries.prototype.getXRange = function (dataSeriesValueType, isHorizontalDirection, hasHighCap, hasLowCap) {
        var xValues = this.getXValues(dataSeriesValueType);
        var _a = this.getHlcValues(dataSeriesValueType), hValues = _a.hValues, lValues = _a.lValues;
        var temp;
        if (isHorizontalDirection) {
            if (this.count() === 1) {
                // TODO check if logic is valid here
                var minValues = hasLowCap ? lValues : xValues;
                var maxValues = hasHighCap ? hValues : xValues;
                var min = minValues.get(0) - 1;
                var max = maxValues.get(0) + 1;
                return new NumberRange_1.NumberRange(min, max);
            }
            else if (this.count() > 1) {
                var min = void 0;
                var max = void 0;
                var minMax = void 0;
                try {
                    // TODO probably can be optimized, make sure there are no memory leaks here
                    minMax = this.webAssemblyContext.NumberUtil.MinMax(hasLowCap ? this.getNativeLowValues() : this.getNativeXValues(), this.dataDistributionCalculator.containsNaN);
                    min = minMax.minD;
                    minMax = this.webAssemblyContext.NumberUtil.MinMax(hasHighCap ? this.getNativeHighValues() : this.getNativeXValues(), this.dataDistributionCalculator.containsNaN);
                    max = minMax.maxD;
                    if (!(0, isRealNumber_1.isRealNumber)(min) || !(0, isRealNumber_1.isRealNumber)(max)) {
                        return new NumberRange_1.NumberRange(0, 0);
                    }
                }
                finally {
                    (0, Deleter_1.deleteSafe)(minMax);
                }
                if (min === max) {
                    return new NumberRange_1.NumberRange(min - 1, max + 1);
                }
                else if (min > max) {
                    temp = min;
                    min = max;
                    max = temp;
                }
                return new NumberRange_1.NumberRange(min, max);
            }
        }
        else {
            if (this.count() === 1) {
                var min = xValues.get(0) - 1;
                var max = xValues.get(0) + 1;
                return new NumberRange_1.NumberRange(min, max);
            }
            else if (this.count() > 1) {
                var min = xValues.get(0);
                var max = xValues.get(this.count() - 1);
                if (!this.dataDistributionCalculator.isSortedAscending) {
                    var minMax = void 0;
                    try {
                        // containsNaN is always false for xValues
                        minMax = this.webAssemblyContext.NumberUtil.MinMax(this.getNativeXValues(), false);
                        if (!(0, isRealNumber_1.isRealNumber)(minMax.minD) || !(0, isRealNumber_1.isRealNumber)(minMax.maxD)) {
                            return new NumberRange_1.NumberRange(0, 0);
                        }
                        min = minMax.minD;
                        max = minMax.maxD;
                    }
                    finally {
                        (0, Deleter_1.deleteSafe)(minMax);
                    }
                }
                if (min === max) {
                    return new NumberRange_1.NumberRange(min - 1, max + 1);
                }
                else if (min > max) {
                    temp = min;
                    min = max;
                    max = temp;
                }
                return new NumberRange_1.NumberRange(min, max);
            }
        }
        return new NumberRange_1.NumberRange(0, 0);
    };
    /** @inheritDoc */
    HlcDataSeries.prototype.getWindowedYRange = function (xRange, getPositiveRange, isXCategoryAxis, dataSeriesValueType, yRangeMode, isHorizontalDirection, hasHighCap, hasLowCap) {
        if (isXCategoryAxis === void 0) { isXCategoryAxis = false; }
        if (dataSeriesValueType === void 0) { dataSeriesValueType = IDataSeries_1.EDataSeriesValueType.Default; }
        if (yRangeMode === void 0) { yRangeMode = YRangeMode_1.EYRangeMode.Visible; }
        if (isHorizontalDirection === void 0) { isHorizontalDirection = false; }
        var _a = this.getHlcValues(dataSeriesValueType), hValues = _a.hValues, lValues = _a.lValues, yValues = _a.yValues;
        // TODO: getPositiveRange
        // if one point
        if (this.count() === 1 && !isHorizontalDirection) {
            if (isHorizontalDirection) {
                var y = yValues.get(0);
                return new NumberRange_1.NumberRange(y, y);
            }
            else {
                var min = Math.min(hValues.get(0), lValues.get(0));
                var max = Math.max(hValues.get(0), lValues.get(0));
                return new NumberRange_1.NumberRange(min, max);
            }
        }
        var indicesRange = isXCategoryAxis
            ? xRange
            : this.getIndicesRange(xRange, false, yRangeMode === YRangeMode_1.EYRangeMode.Visible ? SearchMode_1.ESearchMode.RoundUp : SearchMode_1.ESearchMode.RoundDown, yRangeMode === YRangeMode_1.EYRangeMode.Visible ? SearchMode_1.ESearchMode.RoundDown : SearchMode_1.ESearchMode.RoundUp);
        var yMin = Number.MAX_VALUE;
        var yMax = Number.NEGATIVE_INFINITY;
        var iMin = Math.max(Math.floor(indicesRange.min), 0);
        var iMax = Math.min(Math.ceil(indicesRange.max), this.count() - 1);
        if (iMax < iMin) {
            return undefined;
        }
        // TODO handle log axis
        // TODO check for memory leaks
        if (isHorizontalDirection) {
            var minMax = void 0;
            try {
                minMax = this.webAssemblyContext.NumberUtil.MinMaxWithIndex(yValues, iMin, iMax - iMin + 1, this.dataDistributionCalculator.containsNaN);
                if (!(0, isRealNumber_1.isRealNumber)(minMax.minD) || !(0, isRealNumber_1.isRealNumber)(minMax.maxD)) {
                    return undefined;
                }
                yMin = minMax.minD;
                yMax = minMax.maxD;
            }
            finally {
                (0, Deleter_1.deleteSafe)(minMax);
            }
        }
        else {
            var maxValues = hasHighCap ? hValues : yValues;
            var minValues = hasLowCap ? lValues : yValues;
            var minMaxOfMaxValues = void 0;
            var minMaxOfMinValues = void 0;
            try {
                minMaxOfMaxValues = this.webAssemblyContext.NumberUtil.MinMaxWithIndex(maxValues, iMin, iMax - iMin + 1, this.dataDistributionCalculator.containsNaN);
                if (!(0, isRealNumber_1.isRealNumber)(minMaxOfMaxValues.minD) || !(0, isRealNumber_1.isRealNumber)(minMaxOfMaxValues.maxD)) {
                    return undefined;
                }
                yMax = minMaxOfMaxValues.maxD;
                minMaxOfMinValues = this.webAssemblyContext.NumberUtil.MinMaxWithIndex(minValues, iMin, iMax - iMin + 1, this.dataDistributionCalculator.containsNaN);
                if (!(0, isRealNumber_1.isRealNumber)(minMaxOfMinValues.minD) || !(0, isRealNumber_1.isRealNumber)(minMaxOfMinValues.maxD)) {
                    return undefined;
                }
                yMin = minMaxOfMinValues.minD;
            }
            finally {
                (0, Deleter_1.deleteSafe)(minMaxOfMaxValues);
                (0, Deleter_1.deleteSafe)(minMaxOfMinValues);
            }
        }
        return new NumberRange_1.NumberRange(yMin, yMax);
    };
    /** @inheritDoc */
    HlcDataSeries.prototype.getOptions = function (excludeData) {
        if (excludeData === void 0) { excludeData = false; }
        var json = _super.prototype.getOptions.call(this, excludeData);
        if (!excludeData) {
            // const dataSize = this.count();
            // const xValues: number[] = new Array(dataSize);
            // const yValues: number[] = new Array(dataSize);
            // const highValues: number[] = new Array(dataSize);
            // const lowValues: number[] = new Array(dataSize);
            // if (this.fifoCapacity && this.fifoSweeping) {
            //     for (let i = 0; i < dataSize; i++) {
            //         xValues[i] = (this.xValues as SCRTFifoVector).getRaw(i);
            //         yValues[i] = (this.yValues as SCRTFifoVector).getRaw(i);
            //         highValues[i] = (this.highValues as SCRTFifoVector).getRaw(i);
            //         lowValues[i] = (this.lowValues as SCRTFifoVector).getRaw(i);
            //     }
            // } else {
            //     for (let i = 0; i < dataSize; i++) {
            //         xValues[i] = this.xValues.get(i);
            //         yValues[i] = this.yValues.get(i);
            //         highValues[i] = this.highValues.get(i);
            //         lowValues[i] = this.lowValues.get(i);
            //     }
            // }
            //  Vroom Vroom!
            var xValues = (0, vectorToArray_1.vectorToArray)(this.xValues, this.webAssemblyContext);
            var yValues = (0, vectorToArray_1.vectorToArray)(this.yValues, this.webAssemblyContext);
            var highValues = (0, vectorToArray_1.vectorToArray)(this.highValues, this.webAssemblyContext);
            var lowValues = (0, vectorToArray_1.vectorToArray)(this.lowValues, this.webAssemblyContext);
            var options = {
                xValues: xValues,
                yValues: yValues,
                highValues: highValues,
                lowValues: lowValues
            };
            Object.assign(json, options);
        }
        return json;
    };
    HlcDataSeries.prototype.getHlcValues = function (dataSeriesValueType) {
        var hValues;
        var lValues;
        var yValues;
        switch (dataSeriesValueType) {
            case IDataSeries_1.EDataSeriesValueType.FinalAnimationValues:
                hValues = this.yFinalAnimationValuesArray[1];
                lValues = this.yFinalAnimationValuesArray[2];
                yValues = this.yFinalAnimationValuesArray[0];
                break;
            case IDataSeries_1.EDataSeriesValueType.InitialAnimationValues:
                hValues = this.yInitialAnimationValuesArray[1];
                lValues = this.yInitialAnimationValuesArray[2];
                yValues = this.yInitialAnimationValuesArray[0];
                break;
            default:
                hValues = this.highValues;
                lValues = this.lowValues;
                yValues = this.yValues;
        }
        return { hValues: hValues, lValues: lValues, yValues: yValues };
    };
    return HlcDataSeries;
}(BaseDataSeries_1.BaseDataSeries));
exports.HlcDataSeries = HlcDataSeries;
