"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.XyRatioFilter = void 0;
var Guard_1 = require("../../../Core/Guard");
var DataFilterType_1 = require("../../../types/DataFilterType");
var IDataSeries_1 = require("../IDataSeries");
var XyFilterBase_1 = require("./XyFilterBase");
var vectorToArray_1 = require("../../../utils/vectorToArray");
/**
 * An XyDataSeries where each point is the ratio of the original series and the given divisorSeries
 */
var XyRatioFilter = /** @class */ (function (_super) {
    __extends(XyRatioFilter, _super);
    function XyRatioFilter(originalSeries, options) {
        var _this = this;
        var _a;
        _this = _super.call(this, originalSeries, options) || this;
        _this.divisorField = XyFilterBase_1.EDataSeriesField.Y;
        Guard_1.Guard.notNull(options.divisorSeries, "divisorSeries");
        _this.divisorSeries = options.divisorSeries;
        _this.divisorField = (_a = options.divisorField) !== null && _a !== void 0 ? _a : _this.divisorField;
        _this.onDivisorDataChanged = _this.onDivisorDataChanged.bind(_this);
        _this.divisorSeries.dataChanged.subscribe(_this.onDivisorDataChanged);
        if (_this.getOriginalCount() > 0) {
            _this.filterAll();
        }
        return _this;
    }
    // @ts-ignore
    XyRatioFilter.prototype.toJSON = function (excludeData) {
        if (excludeData === void 0) { excludeData = false; }
        var json = _super.prototype.toJSON.call(this, excludeData);
        var options = json.options;
        if (!excludeData) {
            options.xValues = (0, vectorToArray_1.vectorToArray)(this.getOriginalXValues(), this.webAssemblyContext);
            options.yValues = (0, vectorToArray_1.vectorToArray)(this.getOriginalYValues(), this.webAssemblyContext);
        }
        var divisorValues = (0, vectorToArray_1.vectorToArray)(this.getDivisorYValues(), this.webAssemblyContext);
        options.filter = {
            type: DataFilterType_1.EDataFilterType.XyRatio,
            options: {
                field: this.field,
                xField: this.xField,
                divisorField: this.divisorField,
                divisorSeries: divisorValues
            }
        };
        return __assign(__assign({}, json), { options: options });
    };
    XyRatioFilter.prototype.filterOnAppend = function (count) {
        if (!this.areSourcesInSync()) {
            return;
        }
        // Use the source's logical "new range" rather than this.count() so we stay correct
        // when the source (or this filter) is FIFO and has rolled past its capacity.
        var originalCount = this.getOriginalCount();
        var newCount = Math.min(count, originalCount);
        var startIndex = Math.max(0, originalCount - newCount);
        var _a = this.filter(startIndex, newCount), xValues = _a.xValues, yValues = _a.yValues;
        this.appendRange(xValues, yValues);
    };
    XyRatioFilter.prototype.filterOnUpdate = function (index) {
        this.update(index, this.getOriginalYValues().get(index) / this.getDivisorYValues().get(index));
    };
    XyRatioFilter.prototype.filterOnInsert = function (startIndex, count) {
        if (!this.areSourcesInSync()) {
            return;
        }
        var _a = this.filter(startIndex, count), xValues = _a.xValues, yValues = _a.yValues;
        this.insertRange(startIndex, xValues, yValues);
    };
    XyRatioFilter.prototype.filterOnRemove = function (startIndex, count) {
        if (!this.areSourcesInSync()) {
            return;
        }
        this.removeRange(startIndex, count);
    };
    XyRatioFilter.prototype.filterAll = function () {
        if (!this.areSourcesInSync()) {
            return;
        }
        this.clear();
        var _a = this.filter(0, this.getOriginalCount()), xValues = _a.xValues, yValues = _a.yValues;
        this.appendRange(xValues, yValues);
    };
    /**
     * Both series must be the same length AND aligned at the latest index before computing the
     * ratio. The latest-X comparison catches the FIFO-at-capacity case where both counts saturate
     * at fifoCapacity even though one series has been appended to and the other has not yet.
     */
    XyRatioFilter.prototype.areSourcesInSync = function () {
        var originalCount = this.getOriginalCount();
        var divisorCount = this.divisorSeries.count();
        if (originalCount !== divisorCount)
            return false;
        if (originalCount === 0)
            return true;
        if (!this.originalSeries.fifoCapacity && !this.divisorSeries.fifoCapacity)
            return true;
        return (this.getOriginalXValues().get(originalCount - 1) ===
            this.divisorSeries.getNativeXValues().get(divisorCount - 1));
    };
    XyRatioFilter.prototype.filter = function (startIndex, count) {
        var xValues = [];
        var yValues = [];
        var xValuesView = (0, vectorToArray_1.vectorToArrayViewF64)(this.getOriginalXValues(), this.webAssemblyContext);
        var yValuesView = (0, vectorToArray_1.vectorToArrayViewF64)(this.getOriginalYValues(), this.webAssemblyContext);
        var divisorValuesView = (0, vectorToArray_1.vectorToArrayViewF64)(this.getDivisorYValues(), this.webAssemblyContext);
        // The original and divisor series may independently be FIFO with their own
        // fifoStartIndex/fifoCapacity. Compute raw indices for each separately.
        var fifoCapacity = this.originalSeries.fifoCapacity;
        var fifoStartIndex = fifoCapacity ? this.originalSeries.fifoStartIndex : 0;
        var rawIdx = function (i) { return (fifoCapacity ? (i + fifoStartIndex) % fifoCapacity : i); };
        var divisorFifoCapacity = this.divisorSeries.fifoCapacity;
        var divisorFifoStartIndex = divisorFifoCapacity ? this.divisorSeries.fifoStartIndex : 0;
        var divisorRawIdx = function (i) {
            return divisorFifoCapacity ? (i + divisorFifoStartIndex) % divisorFifoCapacity : i;
        };
        // TODO check if metadata is needed here
        for (var i = startIndex; i < startIndex + count; i++) {
            var r = rawIdx(i);
            xValues.push(xValuesView[r]);
            yValues.push(yValuesView[r] / divisorValuesView[divisorRawIdx(i)]);
        }
        return { xValues: xValues, yValues: yValues };
    };
    XyRatioFilter.prototype.getDivisorYValues = function () {
        var divY = this.divisorSeries.getNativeYValues();
        if (this.divisorSeries.type === IDataSeries_1.EDataSeriesType.Xyy) {
            var xyySeries = this.divisorSeries;
            divY = (0, XyFilterBase_1.switchData)(this.divisorField, xyySeries.getNativeYValues(), xyySeries.getNativeY1Values());
        }
        else if (this.divisorSeries.type === IDataSeries_1.EDataSeriesType.Xyz) {
            var xyzSeries = this.divisorSeries;
            divY = (0, XyFilterBase_1.switchData)(this.field, xyzSeries.getNativeYValues(), xyzSeries.getNativeZValues());
        }
        else if (this.divisorSeries.type === IDataSeries_1.EDataSeriesType.Ohlc) {
            var ohlcSeries = this.divisorSeries;
            divY = (0, XyFilterBase_1.switchData)(this.field, ohlcSeries.getNativeYValues(), ohlcSeries.getNativeOpenValues(), ohlcSeries.getNativeHighValues(), ohlcSeries.getNativeLowValues());
        }
        return divY;
    };
    XyRatioFilter.prototype.onDivisorDataChanged = function (args) {
        var changeType = args.changeType, name = args.name, index = args.index, count = args.count;
        switch (changeType) {
            case IDataSeries_1.EDataChangeType.Append:
                this.filterOnAppend(count);
                break;
            case IDataSeries_1.EDataChangeType.Clear:
                this.onClear();
                break;
            case IDataSeries_1.EDataChangeType.Insert:
                this.filterOnInsert(index, count);
                break;
            case IDataSeries_1.EDataChangeType.Remove:
                this.filterOnRemove(index, count);
                break;
            case IDataSeries_1.EDataChangeType.Update:
                this.filterOnUpdate(index);
                break;
            default:
                break;
        }
    };
    return XyRatioFilter;
}(XyFilterBase_1.XyFilterBase));
exports.XyRatioFilter = XyRatioFilter;
