"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.UniformContoursDrawingProvider = void 0;
var app_1 = require("../../../../constants/app");
var Deleter_1 = require("../../../../Core/Deleter");
var Guard_1 = require("../../../../Core/Guard");
var Rect_1 = require("../../../../Core/Rect");
var parseColor_1 = require("../../../../utils/parseColor");
var TextureCache_1 = require("../../../Drawing/TextureCache");
var NativeObject_1 = require("../../Helpers/NativeObject");
var CanvasTexture_1 = require("../../TextureManager/CanvasTexture");
var BaseHeatmapRenderableSeries_1 = require("../BaseHeatmapRenderableSeries");
var constants_1 = require("../constants");
var BaseSeriesDrawingProvider_1 = require("./BaseSeriesDrawingProvider");
/**
 * Used internally - a drawing provider performs drawing for a {@link UniformContoursDrawingProvider} using
 * our WebAssembly WebGL rendering engine
 */
var UniformContoursDrawingProvider = /** @class */ (function (_super) {
    __extends(UniformContoursDrawingProvider, _super);
    /**
     * Creates an instance of the {@link UniformContoursRenderableSeries}
     * @param webAssemblyContext The {@link TSciChart | SciChart 2D WebAssembly Context} containing native methods and
     * access to our WebGL2 Engine and WebAssembly numerical methods
     * @param parentSeries the parent {@link UniformContoursDrawingProvider} which this drawing provider is attached to
     */
    function UniformContoursDrawingProvider(webAssemblyContext, parentSeries) {
        var _this = _super.call(this, webAssemblyContext, parentSeries) || this;
        _this.heightsTextureCache = new TextureCache_1.TextureCache(webAssemblyContext);
        _this.onSeriesPropertyChange(constants_1.PROPERTY.DATA_SERIES);
        _this.onSeriesPropertyChange(constants_1.PROPERTY.COLOR_MAP);
        return _this;
    }
    /**
     * @inheritDoc
     */
    UniformContoursDrawingProvider.prototype.delete = function () {
        this.heightsTextureCache = (0, Deleter_1.deleteSafe)(this.heightsTextureCache);
        this.heightData = (0, Deleter_1.deleteSafe)(this.heightData);
        this.paletteTexture = (0, Deleter_1.deleteSafe)(this.paletteTexture);
        _super.prototype.delete.call(this);
    };
    /**
     * @inheritDoc
     */
    UniformContoursDrawingProvider.prototype.onSeriesPropertyChange = function (propertyName) {
        var recreatePalette = propertyName === constants_1.PROPERTY.COLOR_MAP || propertyName.includes(BaseHeatmapRenderableSeries_1.COLOR_MAP_PREFIX);
        var recreateHeightmap = propertyName === constants_1.PROPERTY.DATA_SERIES;
        if (recreatePalette) {
            this.paletteTexture = (0, Deleter_1.deleteSafe)(this.paletteTexture);
            if (this.parentSeries.colorMap && this.parentSeries.colorMap.gradientStops) {
                // create palette texture at size 256x1
                this.paletteTexture = this.createPaletteTexture(256, 1, this.parentSeries.colorMap.gradientStops);
            }
            else {
                this.paletteTexture = this.createPaletteTexture(256, 1, undefined);
            }
        }
        if (recreateHeightmap) {
            // console.log("Delete/recreating heightmap texture");
            var dataSeries = this.parentSeries.dataSeries;
            if (dataSeries) {
                // create heightmap texture at same size as the dataSeries array
                var heightsTexture = this.heightsTextureCache.create(dataSeries.arrayWidth, dataSeries.arrayHeight, this.webAssemblyContext.eTSRTextureFormat.TSR_TEXTUREFORMAT_R32F);
                // Set whether to use interpolation for the Heatmap or not
                this.webAssemblyContext.SCRTSetTextureLinearSamplerEnabled(heightsTexture, true);
            }
        }
    };
    /**
     * @inheritDoc
     */
    UniformContoursDrawingProvider.prototype.draw = function (renderContext, renderPassData) {
        var _this = this;
        var _a, _b;
        var heightsTexture = (_a = this.heightsTextureCache) === null || _a === void 0 ? void 0 : _a.value;
        if (heightsTexture) {
            var dataSeries = this.parentSeries.dataSeries;
            this.webAssemblyContext.SCRTFillTextureFloat32(heightsTexture, dataSeries.arrayWidth, dataSeries.arrayHeight, dataSeries.getNormalizedVector((_b = this.parentSeries.colorMap) !== null && _b !== void 0 ? _b : this.getDefaultColorMap(dataSeries)));
            // DEBUG CODE: REMOVE AFTER DEVELOPMENT COMPLETE
            // renderContext.drawTexture(this.heightsTexture, 10, 100, 256, 256);
            // renderContext.drawTexture(this.paletteTexture.getTexture(), 310, 100, 256, 256);
            // END DEBUG CODE
            var cParams_1 = this.parentSeries.getContourDrawingParams();
            var isVerticalChart = renderPassData.isVerticalChart;
            var x_1 = renderPassData.xCoordinateCalculator.getCoordinate(cParams_1.xMin);
            var y_1 = renderPassData.yCoordinateCalculator.getCoordinate(cParams_1.yMin);
            var width_1 = renderPassData.xCoordinateCalculator.getCoordinate(cParams_1.xMax);
            var height_1 = renderPassData.yCoordinateCalculator.getCoordinate(cParams_1.yMax);
            var textureWidth = Math.abs(x_1 - width_1);
            var drawContoursFn = function () {
                var _a;
                if ((_a = cParams_1.zLevels) === null || _a === void 0 ? void 0 : _a.length) {
                    var dataMin = cParams_1.dataZRange.min;
                    var dataDiff = cParams_1.dataZRange.diff;
                    if (dataDiff <= 0)
                        return;
                    // For each explicit level draw a single contour line. Pick zStep = dataDiff so the shader's
                    // contourLinesCount = 1, and pick a tight ±0.5-of-data-range bound so any phantom periodic
                    // line at levelNorm ± 1 falls outside the bounds check.
                    for (var _i = 0, _b = cParams_1.zLevels; _i < _b.length; _i++) {
                        var level = _b[_i];
                        var levelNorm = (level - dataMin) / dataDiff;
                        var normMin = Math.max(0, levelNorm - 0.5);
                        var normMax = Math.min(1, levelNorm + 0.5);
                        var zMinCall = dataMin + normMin * dataDiff;
                        var zMaxCall = dataMin + normMax * dataDiff;
                        var zOffsetCall = levelNorm * (zMaxCall - zMinCall);
                        _this.drawContours(renderContext, x_1, y_1, width_1, height_1, zMinCall, zMaxCall, zOffsetCall, dataDiff, cParams_1.majorLineStyle, cParams_1.dataZRange);
                    }
                    return;
                }
                if (_this.parentSeries.minorsPerMajor > 0) {
                    _this.drawContours(renderContext, x_1, y_1, width_1, height_1, cParams_1.zMin, cParams_1.zMax, cParams_1.zOffset, cParams_1.minorStepZ, cParams_1.minorLineStyle, cParams_1.dataZRange);
                }
                _this.drawContours(renderContext, x_1, y_1, width_1, height_1, cParams_1.zMin, cParams_1.zMax, cParams_1.zOffset, cParams_1.majorStepZ, cParams_1.majorLineStyle, cParams_1.dataZRange);
            };
            if (isVerticalChart) {
                var hasFlippedXCoordinates = !renderPassData.xCoordinateCalculator.hasFlippedCoordinates;
                var seriesViewRect = this.parentSeries.parentSurface.seriesViewRect;
                var clipRect = Rect_1.Rect.intersect(this.parentSeries.parentSurface.clipRect, seriesViewRect);
                renderContext.setTranslationRotationAndClip(clipRect, seriesViewRect.x, seriesViewRect.y + textureWidth + (hasFlippedXCoordinates ? width_1 : x_1), -90);
                width_1 = hasFlippedXCoordinates ? textureWidth : 0;
                x_1 = hasFlippedXCoordinates ? 0 : textureWidth;
                drawContoursFn();
            }
            else {
                drawContoursFn();
            }
        }
    };
    UniformContoursDrawingProvider.prototype.drawContours = function (renderContext, x, y, width, height, zMin, zMax, zOffset, zStep, lineStyle, dataZRange) {
        // Compute params for contours
        var floatParams = (0, NativeObject_1.getVector4)(this.webAssemblyContext, 0, 1, 0, 0);
        var contourParams = new this.webAssemblyContext.SCRTContourParams();
        var zDiff = zMax - zMin;
        var offset = zOffset / zDiff;
        var strokeColor = (0, parseColor_1.parseColorToTArgb)(lineStyle.color);
        contourParams.SetColorVector(strokeColor.red / 255, strokeColor.green / 255, strokeColor.blue / 255, strokeColor.opacity / 255);
        var contourLinesCount = dataZRange.diff / zStep;
        contourParams.SetParamsAVector(lineStyle.strokeThickness, contourLinesCount, -offset, 0);
        var normMin = (zMin - dataZRange.min) / dataZRange.diff;
        var normMax = (zMax - dataZRange.min) / dataZRange.diff;
        //console.log(contourLinesCount, zMin, zMax, normMin, normMax, offset);
        contourParams.SetParamsBVector(normMin, normMax, 0, 0);
        // Draw major contour lines
        var nativeContext = renderContext.getNativeContext();
        // console.log(`viewRect: ${viewRect.x}, ${viewRect.y}, ${viewRect.width}, ${viewRect.height}`);
        // console.log(`contours bounds: ${startX}, ${startY}, ${endX}, ${endY}`);
        var heightsTexture = this.heightsTextureCache.value;
        // draw as a single strip with 4 verts
        var quadVerts = (0, NativeObject_1.getVectorColorTextureVertex)(this.webAssemblyContext);
        var bottomLeft = (0, NativeObject_1.getTextureVertex)(this.webAssemblyContext, x, y, app_1.NEUTRAL_COLOR, 0, 0);
        quadVerts.push_back(bottomLeft);
        var topLeft = (0, NativeObject_1.getTextureVertex)(this.webAssemblyContext, width, y, app_1.NEUTRAL_COLOR, 1, 0);
        quadVerts.push_back(topLeft);
        var bottomRight = (0, NativeObject_1.getTextureVertex)(this.webAssemblyContext, x, height, app_1.NEUTRAL_COLOR, 0, 1);
        quadVerts.push_back(bottomRight);
        var topRight = (0, NativeObject_1.getTextureVertex)(this.webAssemblyContext, width, height, app_1.NEUTRAL_COLOR, 1, 1);
        quadVerts.push_back(topRight);
        var drawParams = new this.webAssemblyContext.SCRTDrawPrimitivesParams();
        drawParams.SetVerticesVec(quadVerts);
        drawParams.SetHeightMapTexture(heightsTexture);
        drawParams.m_vPackedFloatParams = floatParams;
        drawParams.SetContourParams(contourParams);
        drawParams.m_Effect = this.webAssemblyContext.SCRTPrimitivesEffect.Heatmap;
        nativeContext.DrawPrimitives(drawParams);
        drawParams.delete();
        contourParams.delete();
    };
    UniformContoursDrawingProvider.prototype.computeHeightMap = function (textureHeight, textureWidth, zValues, isVerticalChart, xFlipped, yFlipped) {
        var _a;
        var arraySize = textureHeight * textureWidth;
        if (((_a = this.heightData) === null || _a === void 0 ? void 0 : _a.size()) !== arraySize) {
            // console.log("Resizing heightmap texture to " + arraySize);
            this.heightData = (0, Deleter_1.deleteSafe)(this.heightData);
            this.heightData = new this.webAssemblyContext.FloatVector();
            this.heightData.resize(arraySize, 0);
        }
        for (var y = 0; y < textureHeight; y++) {
            for (var x = 0; x < textureWidth; x++) {
                var zValue = !isVerticalChart
                    ? zValues[!yFlipped ? textureHeight - 1 - y : y][xFlipped ? textureWidth - x - 1 : x]
                    : zValues[!yFlipped ? textureWidth - 1 - x : x][xFlipped ? textureHeight - y - 1 : y];
                // Todo: Set into a javascript array then bulk set the array on heightData
                this.heightData.set(y * textureWidth + x, isNaN(zValue) ? -1.0 : zValue);
            }
        }
        return this.heightData;
    };
    UniformContoursDrawingProvider.prototype.createPaletteTexture = function (width, height, gradientStops) {
        if (app_1.IS_TEST_ENV) {
            return undefined;
        }
        Guard_1.Guard.isTrue(width > 0, "width must be greater than 0");
        Guard_1.Guard.isTrue(height > 0, "height must be greater than 0");
        var canvasTexture = new CanvasTexture_1.CanvasTexture(this.webAssemblyContext, width, height);
        canvasTexture.clear();
        var ctx = canvasTexture.getContext();
        // BEGIN: Drawing gradient rectangle on canvas2D
        var x1 = 0;
        var y1 = 0;
        var x2 = width;
        var y2 = 0;
        if (gradientStops) {
            var gradient_1 = ctx.createLinearGradient(x1, y1, x2, y2);
            gradientStops.forEach(function (el) {
                gradient_1.addColorStop(el.offset, el.color);
            });
            ctx.fillStyle = gradient_1;
        }
        else {
            ctx.fillStyle = "black";
        }
        ctx.fillRect(0, 0, width, height);
        // END: Drawing gradient rectangle on canvas2D
        canvasTexture.copyTexture();
        return canvasTexture;
    };
    UniformContoursDrawingProvider.prototype.getDefaultColorMap = function (dataSeries) {
        var zRange = dataSeries.zRange;
        return { minimum: zRange.min, maximum: zRange.max };
    };
    return UniformContoursDrawingProvider;
}(BaseSeriesDrawingProvider_1.BaseSeriesDrawingProvider));
exports.UniformContoursDrawingProvider = UniformContoursDrawingProvider;
