"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.FastRectangleRenderableSeries = void 0;
var Deleter_1 = require("../../../Core/Deleter");
var NumberRange_1 = require("../../../Core/NumberRange");
var ColumnMode_1 = require("../../../types/ColumnMode");
var DataPointWidthMode_1 = require("../../../types/DataPointWidthMode");
var SeriesType_1 = require("../../../types/SeriesType");
var ValueName_1 = require("../../../types/ValueName");
var IDataSeries_1 = require("../../Model/IDataSeries");
var IThemeProvider_1 = require("../../Themes/IThemeProvider");
var SciChartSurfaceBase_1 = require("../SciChartSurfaceBase");
var BaseRenderableSeries_1 = require("./BaseRenderableSeries");
var constants_1 = require("./constants");
var RectangleSeriesDrawingProvider_1 = require("./DrawingProviders/RectangleSeriesDrawingProvider");
var RectangleSeriesHitTestProvider_1 = require("./HitTest/RectangleSeriesHitTestProvider");
var RectangleSeriesDataLabelProvider_1 = require("./DataLabels/RectangleSeriesDataLabelProvider");
var ResamplingMode_1 = require("../../Numerics/Resamplers/ResamplingMode");
/**
 * Defines a rectangle-series or JavaScript rectangle chart type in the SciChart's High Performance Real-time
 * {@link https://www.scichart.com/javascript-chart-features | JavaScript Charts}
 * @remarks
 * To add a rectangle series to a {@link SciChartSurface} you need to declare both the {@link FastRectangleRenderableSeries | RenderableSeries}
 * and a {@link XyNDataSeries | DataSeries}.
 *
 * ---
 * 📚 Docs: {@link https://www.scichart.com/documentation/js/v4/2d-charts/chart-types/fast-rectangle-renderable-series/}
 */
var FastRectangleRenderableSeries = /** @class */ (function (_super) {
    __extends(FastRectangleRenderableSeries, _super);
    /**
     * Creates an instance of the {@link FastRectangleRenderableSeries}
     * @param webAssemblyContext The {@link TSciChart | SciChart WebAssembly Context} containing
     * native methods and access to our WebGL2 WebAssembly Drawing Engine
     * @param options optional parameters of type {@link IFastRectangleRenderableSeriesOptions} applied when constructing the series type
     *
     * ---
     * 📚 Docs: {@link https://www.scichart.com/documentation/js/v4/2d-charts/chart-types/fast-rectangle-renderable-series/}
     */
    function FastRectangleRenderableSeries(webAssemblyContext, options) {
        var _this = this;
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        if (options)
            options.resamplingMode = (_a = options.resamplingMode) !== null && _a !== void 0 ? _a : ResamplingMode_1.EResamplingMode.None;
        _this = _super.call(this, webAssemblyContext, options) || this;
        /** @inheritDoc */
        _this.type = SeriesType_1.ESeriesType.RectangleSeries;
        _this.defaultY1Property = 0;
        _this.fillProperty = SciChartSurfaceBase_1.SciChartSurfaceBase.DEFAULT_THEME.columnFillBrush;
        _this.dataPointWidthProperty = 1;
        _this.dataPointWidthModeProperty = DataPointWidthMode_1.EDataPointWidthMode.Range;
        _this.columnXModeProperty = ColumnMode_1.EColumnMode.Mid;
        _this.columnYModeProperty = ColumnMode_1.EColumnYMode.TopBottom;
        _this.topCornerRadiusProperty = 0;
        _this.bottomCornerRadiusProperty = 0;
        _this.fillProperty = (_b = options === null || options === void 0 ? void 0 : options.fill) !== null && _b !== void 0 ? _b : _this.fillProperty;
        _this.defaultY1Property = (_c = options === null || options === void 0 ? void 0 : options.defaultY1) !== null && _c !== void 0 ? _c : _this.defaultY1Property;
        _this.dataPointWidthProperty = (_d = options === null || options === void 0 ? void 0 : options.dataPointWidth) !== null && _d !== void 0 ? _d : _this.dataPointWidthProperty;
        _this.dataPointWidthModeProperty = (_e = options === null || options === void 0 ? void 0 : options.dataPointWidthMode) !== null && _e !== void 0 ? _e : _this.dataPointWidthModeProperty;
        _this.fillLinearGradientProperty = (_f = options === null || options === void 0 ? void 0 : options.fillLinearGradient) !== null && _f !== void 0 ? _f : _this.fillLinearGradientProperty;
        _this.topCornerRadiusProperty = (_g = options === null || options === void 0 ? void 0 : options.topCornerRadius) !== null && _g !== void 0 ? _g : _this.topCornerRadiusProperty;
        _this.bottomCornerRadiusProperty = (_h = options === null || options === void 0 ? void 0 : options.bottomCornerRadius) !== null && _h !== void 0 ? _h : _this.bottomCornerRadiusProperty;
        _this.columnXModeProperty = (_j = options === null || options === void 0 ? void 0 : options.columnXMode) !== null && _j !== void 0 ? _j : _this.columnXModeProperty;
        _this.columnYModeProperty = (_k = options === null || options === void 0 ? void 0 : options.columnYMode) !== null && _k !== void 0 ? _k : _this.columnYModeProperty;
        _this.customTextureOptionsProperty = options === null || options === void 0 ? void 0 : options.customTextureOptions;
        // Must be called here for the series type to be available
        if ((_l = _this.paletteProvider) === null || _l === void 0 ? void 0 : _l.onAttached) {
            (_m = _this.paletteProvider) === null || _m === void 0 ? void 0 : _m.onAttached(_this);
        }
        if (!_this.dataLabelProviderProperty) {
            _this.dataLabelProviderProperty = new RectangleSeriesDataLabelProvider_1.RectangleSeriesDataLabelProvider(options === null || options === void 0 ? void 0 : options.dataLabels);
            _this.dataLabelProviderProperty.onAttach(_this.webAssemblyContext, _this);
        }
        if (options === null || options === void 0 ? void 0 : options.animation) {
            _this.animationQueue.push(options.animation);
        }
        return _this;
    }
    FastRectangleRenderableSeries.prototype.addDrawingProviders = function (webAssemblyContext, options) {
        this.drawingProviders.push(new RectangleSeriesDrawingProvider_1.RectangleSeriesDrawingProvider(webAssemblyContext, this));
    };
    FastRectangleRenderableSeries.prototype.applyTheme = function (themeProvider) {
        _super.prototype.applyTheme.call(this, themeProvider);
        var previousThemeProvider = this.parentSurface.previousThemeProvider;
        if (this.fill === previousThemeProvider.columnFillBrush) {
            this.fill = themeProvider.columnFillBrush;
        }
        if (this.stroke === previousThemeProvider.columnLineColor) {
            this.stroke = themeProvider.columnLineColor;
        }
    };
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "defaultY1", {
        /**
         * Gets or Sets a common y1 value for all rectangles if y1Values are not provided.  Default 0
         */
        get: function () {
            return this.defaultY1Property;
        },
        set: function (value) {
            this.defaultY1Property = value;
            this.notifyPropertyChanged(constants_1.PROPERTY.DEFAULT_Y1);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "fill", {
        /**
         * Gets or Sets fill property
         */
        get: function () {
            return (0, IThemeProvider_1.stripAutoColor)(this.fillProperty);
        },
        set: function (htmlColorCode) {
            if (this.fillProperty !== htmlColorCode) {
                this.fillProperty = htmlColorCode;
                this.notifyPropertyChanged(constants_1.PROPERTY.FILL);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "fillLinearGradient", {
        /**
         * Gets or sets the fill as a gradient brush
         */
        get: function () {
            return this.fillLinearGradientProperty;
        },
        set: function (gradientBrushParams) {
            // We need this check, to prevent creating new Texture if we set the same value
            if (gradientBrushParams !== this.fillLinearGradientProperty) {
                this.fillLinearGradientProperty = gradientBrushParams;
                this.notifyPropertyChanged(constants_1.PROPERTY.FILL_LINEAR_GRADIENT);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "columnXMode", {
        /**
         * Gets or Sets how the x values and optional x1 values are interpreted
         */
        get: function () {
            return this.columnXModeProperty;
        },
        set: function (value) {
            if (this.columnXModeProperty !== value) {
                this.columnXModeProperty = value;
                this.notifyPropertyChanged("COLUMN_MODE");
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "columnYMode", {
        /**
         * Gets or Sets how the y values and optional y1 values are interpreted
         */
        get: function () {
            return this.columnYModeProperty;
        },
        set: function (value) {
            if (this.columnYModeProperty !== value) {
                this.columnYModeProperty = value;
                this.notifyPropertyChanged("COLUMN_MODE");
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "dataPointWidth", {
        /**
         * Gets or Sets a value used to calculate the width of rectangles in X direction.
         * By default the value is treated as data range, since rectangle series do not tend to be evenly spaced.
         * To specify if the value should be treated as relative, absolute, or based on range use {@link dataPointWidthMode}
         * Note that Absolute mode does not work well with autoRange due to circularity between the range calculation and the axis layout.
         */
        get: function () {
            return this.dataPointWidthProperty;
        },
        set: function (dataPointWidth) {
            this.dataPointWidthProperty = dataPointWidth;
            this.notifyPropertyChanged(constants_1.PROPERTY.DATA_POINT_WIDTH);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "dataPointWidthMode", {
        /**
         * Gets or sets the mode which determines how dataPointWidth in X direction is interpreted. Available values are {@link EDataPointWidthMode}.  Default Range.
         */
        get: function () {
            return this.dataPointWidthModeProperty;
        },
        set: function (value) {
            this.dataPointWidthModeProperty = value;
            this.notifyPropertyChanged(constants_1.PROPERTY.DATA_POINT_WIDTH_MODE);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "topCornerRadius", {
        /**
         * Gets or sets the top corner radius, to give the rectangles top rounded corners. Default is 0
         */
        get: function () {
            return this.topCornerRadiusProperty;
        },
        set: function (cornerRadius) {
            this.topCornerRadiusProperty = cornerRadius;
            this.notifyPropertyChanged(constants_1.PROPERTY.TOP_CORNER_RADIUS);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "bottomCornerRadius", {
        /**
         * Gets or sets the bottom corner radius, to give the rectangles bottom rounded corners. Default is 0
         */
        get: function () {
            return this.bottomCornerRadiusProperty;
        },
        set: function (cornerRadius) {
            this.bottomCornerRadiusProperty = cornerRadius;
            this.notifyPropertyChanged(constants_1.PROPERTY.BOTTOM_CORNER_RADIUS);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FastRectangleRenderableSeries.prototype, "customTextureOptions", {
        /**
         * Gets or sets options to use a custom texture brush
         */
        get: function () {
            return this.customTextureOptionsProperty;
        },
        /**
         * Gets or sets options to use a custom texture brush
         */
        set: function (customTextureOptions) {
            // We need this check, to prevent creating new Texture if we set the same value
            if (customTextureOptions !== this.customTextureOptionsProperty) {
                this.customTextureOptionsProperty = customTextureOptions;
                this.notifyPropertyChanged(constants_1.PROPERTY.CUSTOM_TEXTURE_OPTIONS);
            }
        },
        enumerable: false,
        configurable: true
    });
    /** @inheritDoc */
    FastRectangleRenderableSeries.prototype.getXRange = function () {
        var count = this.dataSeries.count();
        var ds = this.dataSeries;
        if ([ColumnMode_1.EColumnMode.MidWidth, ColumnMode_1.EColumnMode.StartWidth].includes(this.columnXMode)) {
            var xValues = ds.getNativeXValues();
            var x1Values = ds.getYValuesByName(ValueName_1.EValueName.X1);
            if (!x1Values) {
                throw new Error("columnXMode ".concat(this.columnXMode, " requires x1 values.  Please use an Xyx or Xyxy dataseries"));
            }
            var minMax = void 0;
            var isMid = this.columnXMode === ColumnMode_1.EColumnMode.MidWidth;
            var min = xValues.get(0);
            var max = xValues.get(ds.count() - 1);
            var temp = void 0;
            try {
                // containsNaN is always false for xValues
                minMax = this.webAssemblyContext.NumberUtil.MinMaxPair(ds.getNativeXValues(), x1Values, isMid ? 0.5 : 1, isMid ? -0.5 : 0, false);
                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);
            // } else if (this.columnXMode === EColumnMode.Width) {
            //     let width = 0;
            //     const xValues = ds.getNativeXValues();
            //     for (let i = 0; i < count; i++) {
            //         width += xValues.get(i);
            //     }
            //     return new NumberRange(0, width);
        }
        else if (this.columnXMode === ColumnMode_1.EColumnMode.StartEnd) {
            var startRange = ds.getXRange(IDataSeries_1.EDataSeriesValueType.Default);
            var endRange = ds.getXRangeByName(IDataSeries_1.EDataSeriesValueType.Default, ValueName_1.EValueName.X1);
            return new NumberRange_1.NumberRange(Math.min(startRange.min, endRange.min), Math.max(startRange.max, endRange.max));
        }
        else {
            var range = _super.prototype.getXRange.call(this);
            var width = this.dataPointWidth;
            if (this.dataPointWidthMode === DataPointWidthMode_1.EDataPointWidthMode.Relative) {
                if (count > 1) {
                    width = (range.diff / (count - 1)) * this.dataPointWidth;
                }
                else {
                    width = 0;
                }
            }
            if (this.dataPointWidthMode === DataPointWidthMode_1.EDataPointWidthMode.Absolute) {
                var cc = this.xAxis.getCurrentCoordinateCalculator();
                width = cc.getDataWidth(this.dataPointWidth) / 2;
            }
            if (this.columnXMode === ColumnMode_1.EColumnMode.Mid) {
                return new NumberRange_1.NumberRange(range.min - width / 2, range.max + width / 2);
            }
            else if (this.columnXMode === ColumnMode_1.EColumnMode.Start) {
                return new NumberRange_1.NumberRange(range.min, range.max + width);
            }
        }
        return new NumberRange_1.NumberRange(0, 0);
    };
    /** @inheritDoc */
    FastRectangleRenderableSeries.prototype.getYRange = function (xVisibleRange, isXCategoryAxis) {
        var y1Values = this.dataSeries.getYValuesByName(ValueName_1.EValueName.Y1);
        if ([ColumnMode_1.EColumnYMode.CenterHeight, ColumnMode_1.EColumnYMode.TopHeight].includes(this.columnYMode)) {
            var isCenterHeightYMode = ColumnMode_1.EColumnYMode.CenterHeight === this.columnYMode;
            var indicesRange = isXCategoryAxis ? xVisibleRange : this.getIndicesRange(xVisibleRange, false);
            var iMin = Math.max(Math.floor(indicesRange.min), 0);
            var iMax = Math.min(Math.ceil(indicesRange.max), this.dataSeries.count() - 1);
            if (iMax < iMin) {
                return undefined;
            }
            var minMax = void 0;
            var yValues = this.dataSeries.getYValuesByName(ValueName_1.EValueName.Y);
            if (y1Values) {
                var min = void 0;
                var max = void 0;
                var minValueMultiplier = isCenterHeightYMode ? -0.5 : -1;
                var maxValueMultiplier = isCenterHeightYMode ? 0.5 : 0;
                try {
                    minMax = this.webAssemblyContext.NumberUtil.MinMaxPairWithIndex(yValues, y1Values, minValueMultiplier, maxValueMultiplier, iMin, iMax - iMin + 1, this.dataSeries.dataDistributionCalculator.containsNaN);
                    min = minMax.minD;
                    max = minMax.maxD;
                }
                finally {
                    (0, Deleter_1.deleteSafe)(minMax);
                }
                return new NumberRange_1.NumberRange(min, max);
            }
            else {
                var yRange = _super.prototype.getYRange.call(this, xVisibleRange, isXCategoryAxis);
                if (!yRange) {
                    return undefined;
                }
                if (isCenterHeightYMode) {
                    return new NumberRange_1.NumberRange(yRange.min - this.defaultY1 / 2, yRange.max + this.defaultY1 / 2);
                }
                else {
                    return new NumberRange_1.NumberRange(yRange.min - this.defaultY1, yRange.max);
                }
            }
        }
        else {
            var yRange = _super.prototype.getYRange.call(this, xVisibleRange, isXCategoryAxis);
            if (!yRange) {
                return undefined;
            }
            if (!y1Values) {
                return new NumberRange_1.NumberRange(Math.min(yRange.min, this.defaultY1), Math.max(yRange.max, this.defaultY1));
            }
            return yRange;
        }
    };
    /** @inheritDoc */
    FastRectangleRenderableSeries.prototype.getIndicesRange = function (xRange, isCategoryData) {
        // Even for sorted data, trying to figure out which rectangles are in view when they can have variable widths is hard and slow.
        return new NumberRange_1.NumberRange(0, this.dataSeries.count() - 1);
    };
    /** @inheritDoc */
    FastRectangleRenderableSeries.prototype.resolveAutoColors = function (index, maxSeries, theme) {
        _super.prototype.resolveAutoColors.call(this, index, maxSeries, theme);
        if (this.fillProperty.startsWith(IThemeProvider_1.AUTO_COLOR)) {
            var color = theme.getFillColor(index, maxSeries, this.webAssemblyContext);
            this.fill = IThemeProvider_1.AUTO_COLOR + this.adjustAutoColor("fill", color);
        }
    };
    /** @inheritDoc */
    FastRectangleRenderableSeries.prototype.toJSON = function (excludeData) {
        if (excludeData === void 0) { excludeData = false; }
        var json = _super.prototype.toJSON.call(this, excludeData);
        var options = {
            columnXMode: this.columnXMode,
            dataPointWidth: this.dataPointWidth,
            dataPointWidthMode: this.dataPointWidthMode,
            defaultY1: this.defaultY1,
            fill: this.fill,
            fillLinearGradient: this.fillLinearGradient,
            topCornerRadius: this.topCornerRadius,
            bottomCornerRadius: this.bottomCornerRadius,
            columnYMode: this.columnYMode
        };
        Object.assign(json.options, options);
        return json;
    };
    /** @inheritDoc */
    FastRectangleRenderableSeries.prototype.newHitTestProvider = function () {
        return new RectangleSeriesHitTestProvider_1.RectangleSeriesHitTestProvider(this, this.webAssemblyContext);
    };
    return FastRectangleRenderableSeries;
}(BaseRenderableSeries_1.BaseRenderableSeries));
exports.FastRectangleRenderableSeries = FastRectangleRenderableSeries;
