"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 __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseValueAxis = void 0;
var Deleter_1 = require("../../../Core/Deleter");
var AxisType_1 = require("../../../types/AxisType");
var NumberArray_1 = require("../../../types/NumberArray");
var SeriesType_1 = require("../../../types/SeriesType");
var vectorToArray_1 = require("../../../utils/vectorToArray");
var XDataSeries_1 = require("../../Model/XDataSeries");
var FlippedIndexCoordinateCalculator_1 = require("../../Numerics/CoordinateCalculators/FlippedIndexCoordinateCalculator");
var IndexCoordinateCalculator_1 = require("../../Numerics/CoordinateCalculators/IndexCoordinateCalculator");
var IndexTickProvider_1 = require("../../Numerics/TickProviders/IndexTickProvider");
var AxisBase2D_1 = require("./AxisBase2D");
var NumericDeltaCalculator_1 = require("./DeltaCalculator/NumericDeltaCalculator");
var NumericLabelProvider_1 = require("./LabelProvider/NumericLabelProvider");
/**
 * @summary A 2D Chart Index Axis type
 * @description This uses explicit base values which are plotted by index (ie evenly spaced) and also used to convert from data x values to indexes.
 * This allows for a non-linear axis with data values interpolated between the base values, meaning that it can support series with different number of points, and series with multiple points on the same x value.
 * BaseValueAxis is continuous, ie gaps are compressed, not removed. It uses Numeric delta calculation and label formatting.
 * For Date/Time based data with gaps removed, use {@link DiscontinuousDateAxis} instead.
 * @remarks
 * Set a {@link BaseValueAxis} on the {@link SciChartSurface.xAxes} property.
 *
 * ---
 * 📚 Docs: {@link https://www.scichart.com/documentation/js/v5/2d-charts/axis-api/axis-types/base-value-axis/}
 */
var BaseValueAxis = /** @class */ (function (_super) {
    __extends(BaseValueAxis, _super);
    /**
     * Creates an instance of a {@link BaseValueAxis}
     * @param webAssemblyContext The {@link TSciChart | SciChart 2D WebAssembly Context} containing native methods and
     * access to our WebGL2 Engine and WebAssembly numerical methods
     * @param options Optional parameters of type {@link IBaseValueAxisOptions} used to configure the axis at instantiation time
     *
     * ---
     * 📚 Docs: TODO
     */
    function BaseValueAxis(webAssemblyContext, options) {
        var _this = this;
        var _a, _b;
        _this = _super.call(this, webAssemblyContext, options) || this;
        _this.type = AxisType_1.EAxisType.BaseValueAxis;
        _this.baseValuesDataSeries = undefined;
        _this.lastBaseValuesDataSeries = undefined;
        _this.lastBaseValuesDataSeriesChangeCount = 0;
        _this.baseValuesDataSeriesFromArray = undefined;
        _this.labelProvider = (_a = options === null || options === void 0 ? void 0 : options.labelProvider) !== null && _a !== void 0 ? _a : new NumericLabelProvider_1.NumericLabelProvider(options);
        _this.tickProvider = new IndexTickProvider_1.IndexTickProvider(_this.webAssemblyContext2D);
        _this.deltaCalculator = new NumericDeltaCalculator_1.NumericDeltaCalculator(webAssemblyContext);
        _this.indexCalculator = new webAssemblyContext.IndexCalculator();
        _this.emptyVector = new webAssemblyContext.SCRTDoubleVector();
        _this.dataGap = (_b = options === null || options === void 0 ? void 0 : options.dataGap) !== null && _b !== void 0 ? _b : 0;
        if (options === null || options === void 0 ? void 0 : options.baseValues) {
            if ("changeCount" in options.baseValues) {
                _this.baseValuesDataSeries = options.baseValues;
            }
            else if ((0, NumberArray_1.isNumberArray)(options.baseValues)) {
                _this.setBaseValuesFromArray(options.baseValues);
            }
            else {
                throw new Error("Invalid baseValues type. Expected IDataSeries or NumberArray");
            }
        }
        return _this;
    }
    Object.defineProperty(BaseValueAxis.prototype, "isLinearAxis", {
        /**
         * @inheritDoc
         */
        get: function () {
            return false;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BaseValueAxis.prototype, "dataGap", {
        /** Gets the normal gap between base values. If this is set to 0, the axis will be in continuous mode where gaps are compressed, not removed. */
        get: function () {
            return this.indexCalculator.dataPointWidth;
        },
        /** Sets the normal gap between base values. If this is set to 0, the axis will be in continuous mode where gaps are compressed, not removed. */
        set: function (value) {
            if (this.indexCalculator.dataPointWidth !== value) {
                this.indexCalculator.dataPointWidth = value;
                this.notifyPropertyChanged("dataGap");
            }
        },
        enumerable: false,
        configurable: true
    });
    BaseValueAxis.prototype.getMajorTickIndex = function (tick) {
        if (this.autoTicks && this.dataGap > 0) {
            var indexCoordCalc = this.getCurrentCoordinateCalculator();
            var indexTick = indexCoordCalc.transformDataToIndex(tick);
            var step = this.majorDelta / this.dataGap;
            var index = indexTick / step;
            return Math.round(index);
        }
        else {
            return _super.prototype.getMajorTickIndex.call(this, tick);
        }
    };
    /** @inheritDoc */
    BaseValueAxis.prototype.prepareRenderData = function () {
        // Update the index calculator before creating coordinate calculator
        // This ensures it works even when the axis is invisible
        this.updateIndexCalculatorBaseValues();
        _super.prototype.prepareRenderData.call(this);
    };
    /** @inheritDoc */
    BaseValueAxis.prototype.getCurrentCoordinateCalculatorInternal = function () {
        var min = this.visibleRange.min;
        var max = this.visibleRange.max;
        var indexMin = this.indexCalculator.GetIndex(min);
        var indexMax = this.indexCalculator.GetIndex(max);
        var offset = this.offset;
        var size = this.axisLength;
        var coordCalc = this.isXAxis !== this.flippedCoordinates
            ? new IndexCoordinateCalculator_1.IndexCoordinateCalculator(this.webAssemblyContext2D, this.indexCalculator, size, min, max, indexMin, indexMax, offset)
            : new FlippedIndexCoordinateCalculator_1.FlippedIndexCoordinateCalculator(this.webAssemblyContext2D, this.indexCalculator, size, min, max, indexMin, indexMax, offset);
        this.updateIndexCalculatorBaseValues();
        return coordCalc;
    };
    /** @inheritDoc */
    BaseValueAxis.prototype.delete = function () {
        this.indexCalculator = (0, Deleter_1.deleteSafe)(this.indexCalculator);
        this.baseValuesDataSeriesFromArray = (0, Deleter_1.deleteSafe)(this.baseValuesDataSeriesFromArray);
        this.emptyVector = (0, Deleter_1.deleteSafe)(this.emptyVector);
        _super.prototype.delete.call(this);
    };
    /** Gets the dataSeries used for the base values.  If this was not set explicitly it will be a reference to the dataSeries of the first renderableSeries */
    BaseValueAxis.prototype.getBaseValues = function () {
        var _this = this;
        var baseValuesDataSeries;
        if (this.baseValuesDataSeries && !this.baseValuesDataSeries.getIsDeleted()) {
            // case where base X values have been set by the user
            baseValuesDataSeries = this.baseValuesDataSeries;
        }
        else {
            // the default case where the first data series is used
            var scs = this.parentSurface;
            var renderableSeries = scs.renderableSeries.asArray().find(function (rs) { return rs.xAxisId === _this.id; });
            if (renderableSeries) {
                if ((renderableSeries === null || renderableSeries === void 0 ? void 0 : renderableSeries.type) === SeriesType_1.ESeriesType.UniformHeatmapSeries) {
                    throw Error("Index Axis is not supported for UniformHeatmapRenderableSeries use NonUniformHeatmapSeries instead");
                }
                else if ((renderableSeries === null || renderableSeries === void 0 ? void 0 : renderableSeries.type) === SeriesType_1.ESeriesType.NonUniformHeatmapSeries) {
                    throw Error("In order to use NonUniformHeatmapSeries with BaseValueAxis please set base X values using xBaseValueAxis.setBaseXValuesFromArray() method");
                }
                if (renderableSeries === null || renderableSeries === void 0 ? void 0 : renderableSeries.isCollection) {
                    var stackedCollection = renderableSeries;
                    if (stackedCollection.size() === 0) {
                        throw Error("BaseStackedCollection should have at least one BaseStackedRenderableSeries");
                    }
                    var firstStackedRS = stackedCollection.get(0);
                    if (firstStackedRS.dataSeries && !firstStackedRS.dataSeries.getIsDeleted()) {
                        baseValuesDataSeries = firstStackedRS.dataSeries;
                    }
                }
                else {
                    // Not stacked renderable series
                    if (renderableSeries.dataSeries && !renderableSeries.dataSeries.getIsDeleted()) {
                        baseValuesDataSeries = renderableSeries.dataSeries;
                    }
                }
            }
        }
        return baseValuesDataSeries;
    };
    /**
     * Set a data series to use as the base values for the axis. The x values will be used, even if the axis is a Y axis
     * @param dataSeries
     */
    BaseValueAxis.prototype.setBaseValues = function (dataSeries) {
        this.baseValuesDataSeries = dataSeries;
        this.notifyPropertyChanged("baseValues");
    };
    BaseValueAxis.prototype.setBaseValuesFromArray = function (values) {
        (0, Deleter_1.deleteSafe)(this.baseValuesDataSeriesFromArray);
        this.baseValuesDataSeriesFromArray = new XDataSeries_1.XDataSeries(this.webAssemblyContext2D, { xValues: values });
        this.setBaseValues(this.baseValuesDataSeriesFromArray);
    };
    BaseValueAxis.prototype.updateIndexCalculatorBaseValues = function () {
        var baseValuesDataSeries = this.getBaseValues();
        if (baseValuesDataSeries && !baseValuesDataSeries.getIsDeleted()) {
            if (baseValuesDataSeries !== this.lastBaseValuesDataSeries ||
                baseValuesDataSeries.changeCount !== this.lastBaseValuesDataSeriesChangeCount) {
                this.updateIndexCalculatorBaseValuesInternal(baseValuesDataSeries.getNativeXValues());
                this.lastBaseValuesDataSeries = baseValuesDataSeries;
                this.lastBaseValuesDataSeriesChangeCount = baseValuesDataSeries.changeCount;
            }
        }
        else {
            this.updateIndexCalculatorBaseValuesInternal(this.emptyVector);
        }
    };
    BaseValueAxis.prototype.updateIndexCalculatorBaseValuesInternal = function (vector) {
        this.indexCalculator.UpdateVec(vector, false);
    };
    /** @inheritDoc */
    BaseValueAxis.prototype.toJSON = function () {
        var json = _super.prototype.toJSON.call(this);
        var baseValues = this.baseValuesDataSeries
            ? (0, vectorToArray_1.vectorToArray)(this.baseValuesDataSeries.getNativeXValues(), this.webAssemblyContext2D)
            : undefined;
        var options = {
            baseValues: baseValues,
            dataGap: this.dataGap
        };
        Object.assign(json.options, options);
        return json;
    };
    return BaseValueAxis;
}(AxisBase2D_1.AxisBase2D));
exports.BaseValueAxis = BaseValueAxis;
