"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSingle3dInternal = void 0;
// @ts-ignore
var WasmModule3D = require("../../_wasm/scichart3d");
var licenseManager2D_1 = require("../../Charting/Visuals/licenseManager2D");
var SciChartDefaults_1 = require("../../Charting/Visuals/SciChartDefaults");
var sciChartInitCommon_1 = require("../../Charting/Visuals/sciChartInitCommon");
var SciChartSurfaceBase_1 = require("../../Charting/Visuals/SciChartSurfaceBase");
var BuildStamp_1 = require("../../Core/BuildStamp");
var DeletableEntity_1 = require("../../Core/DeletableEntity");
var logger_1 = require("../../utils/logger");
var performance_1 = require("../../utils/performance");
var SciChart3DSurface_1 = require("./SciChart3DSurface");
var preRun_1 = require("../../Charting/Visuals/preRun");
var Globals_1 = require("../../Core/Globals");
var WebGpuHelper_1 = require("../../Core/WebGpuHelper");
var app_1 = require("../../constants/app");
var createSingle3dInternal = function (divElement, options) { return __awaiter(void 0, void 0, void 0, function () {
    var canvases, loader, loaderDiv, mark, locateFile, preinitializedWebGPUDevice, moduleOptions;
    var _a, _b, _c, _d, _e, _f;
    return __generator(this, function (_g) {
        switch (_g.label) {
            case 0:
                if (!app_1.IS_WEB_GPU) return [3 /*break*/, 2];
                return [4 /*yield*/, WebGpuHelper_1.WebGpuHelper.initializeWebGPUDevice()];
            case 1:
                _g.sent();
                _g.label = 2;
            case 2:
                canvases = sciChartInitCommon_1.default.initCanvas(divElement, (_a = options === null || options === void 0 ? void 0 : options.widthAspect) !== null && _a !== void 0 ? _a : 0, (_b = options === null || options === void 0 ? void 0 : options.heightAspect) !== null && _b !== void 0 ? _b : 0, undefined, (_c = options === null || options === void 0 ? void 0 : options.disableAspect) !== null && _c !== void 0 ? _c : SciChartDefaults_1.SciChartDefaults.disableAspect, options === null || options === void 0 ? void 0 : options.touchAction);
                loader = ((_d = options === null || options === void 0 ? void 0 : options.loader) !== null && _d !== void 0 ? _d : SciChartDefaults_1.SciChartDefaults.defaultLoader);
                loaderDiv = (_e = loader.addChartLoader) === null || _e === void 0 ? void 0 : _e.call(loader, canvases.domDivContainer, (_f = options === null || options === void 0 ? void 0 : options.theme) !== null && _f !== void 0 ? _f : SciChartSurfaceBase_1.SciChartSurfaceBase.DEFAULT_THEME);
                mark = performance_1.PerformanceDebugHelper.mark(performance_1.EPerformanceMarkType.EngineInitStart, {
                    parentContextId: canvases.domCanvas2D.id
                });
                locateFile = (0, SciChartSurfaceBase_1.getLocateFile)(SciChart3DSurface_1.sciChartConfig3D);
                if (!WebGpuHelper_1.WebGpuHelper.getWebGpuSupported()) return [3 /*break*/, 4];
                return [4 /*yield*/, WebGpuHelper_1.WebGpuHelper.initializeWebGPUDevice()];
            case 3:
                preinitializedWebGPUDevice = _g.sent();
                _g.label = 4;
            case 4:
                moduleOptions = { locateFile: locateFile, noInitialRun: true, canvas: canvases.domCanvasWebGL, preRun: preRun_1.preRun };
                if (preinitializedWebGPUDevice) {
                    moduleOptions.preinitializedWebGPUDevice = preinitializedWebGPUDevice;
                }
                return [2 /*return*/, new Promise(function (resolve, reject) {
                        // @ts-ignore
                        new WasmModule3D(moduleOptions)
                            .then(function (wasmContext) {
                            var _a, _b, _c;
                            (_a = loader.removeChartLoader) === null || _a === void 0 ? void 0 : _a.call(loader, canvases.domDivContainer, loaderDiv);
                            // @ts-ignore
                            wasmContext.doNotCaptureKeyboard = true;
                            licenseManager2D_1.licenseManager.applyLicense(wasmContext, "3D single");
                            var revocable = (0, DeletableEntity_1.createWasmContextRevocableProxy)(wasmContext, canvases.domCanvas2D.id);
                            var customResolve = function (res) {
                                res.sciChart3DSurface.addDeletable({
                                    delete: function () {
                                        revocable.revoke();
                                        revocable = undefined;
                                    }
                                });
                                performance_1.PerformanceDebugHelper.mark(performance_1.EPerformanceMarkType.EngineInitEnd, {
                                    relatedId: mark === null || mark === void 0 ? void 0 : mark.detail.relatedId,
                                    contextId: res.sciChart3DSurface.id,
                                    parentContextId: canvases.domCanvas2D.id
                                });
                                resolve(res);
                            };
                            initDrawEngineSingleChart(revocable.proxy, canvases, customResolve, (_b = options === null || options === void 0 ? void 0 : options.theme) !== null && _b !== void 0 ? _b : SciChartSurfaceBase_1.SciChartSurfaceBase.DEFAULT_THEME);
                            //Flag which ensures Typescript side drives emscripten rendering (one render per draw request)
                            // @ts-ignore
                            wasmContext.TSRSetDrawRequestsEnabled((_c = !(options === null || options === void 0 ? void 0 : options.disableEngineLoop)) !== null && _c !== void 0 ? _c : true);
                            // initDrawEngineSingleChart(
                            //     wasmContext,
                            //     canvases,
                            //     resolve,
                            //     (options?.theme as IThemeProvider) ?? SciChartSurfaceBase.DEFAULT_THEME
                            // );
                            (0, BuildStamp_1.checkBuildStamp)(wasmContext);
                        })
                            .catch(function (ex) {
                            var _a;
                            (_a = loader.removeChartLoader) === null || _a === void 0 ? void 0 : _a.call(loader, canvases.domDivContainer, loaderDiv);
                            reject("Could not load SciChart WebAssembly module.\n                    Check your build process and ensure that your \"scichart3d.wasm\" and \"scichart3d.js\" files are from the same version");
                            throw ex;
                        });
                    })];
        }
    });
}); };
exports.createSingle3dInternal = createSingle3dInternal;
// SINGLE CHART FUNCTIONS
/** @ignore */
var initDrawEngineSingleChart = function (wasmContext, canvases, resolve, theme) {
    var width = canvases.domCanvas2D.width;
    var height = canvases.domCanvas2D.height;
    // @ts-ignore
    // wasmContext.preRun.push(() => (ENV.SDL_EMSCRIPTEN_KEYBOARD_ELEMENT = "#chart_WebGL"));
    var scs;
    wasmContext.canvas = canvases.domCanvasWebGL;
    var chartInitializer = {
        InitializeChart: function () {
            scs = new SciChart3DSurface_1.SciChart3DSurface(wasmContext, { canvases: canvases });
            scs.applyTheme(theme);
            Globals_1.sciChart3DSingleDestinations.push({
                canvasElementId: canvases.domCanvasWebGL.id,
                sciChartSurface: scs,
                width: width,
                height: height
            });
            scs.setDestinations(Globals_1.sciChart3DSingleDestinations);
            scs.addDeletable({
                delete: function () {
                    // Halt the engine
                    wasmContext.TSRRequestExit();
                    frameRenderer3D.delete();
                    wasmContext.SCRTGetGlobalRenderLoopManager().SetFrameRenderer(null);
                    wasmContext.SCRTGetGlobalRenderLoopManager().delete();
                    wasmContext.SCRTSetGlobalRenderLoopManager(null);
                    licenseManager2D_1.licenseManager.clear();
                }
            });
            setTimeout(function () {
                scs.invalidateElement();
                licenseManager2D_1.licenseManager.updateLicenseDisplay(scs);
                var unsub = sciChartInitCommon_1.default.subscribeToResize(canvases.domChartRoot, canvases.aspect, scs);
                scs.addDeletable(unsub);
                scs.setIsInitialized();
                resolve({ wasmContext: wasmContext, sciChart3DSurface: scs });
            }, 0);
        },
        Draw: function (canvasId) {
            logger_1.Logger.debug("Draw", canvasId);
            if (scs.isInitialized) {
                scs.doDrawingLoop();
            }
        },
        Update: function (deltaTime) {
            //Logger.log("SciChart3DSurface.ts Update()");
        },
        ShutDownChart: function () {
            //Logger.log("SciChart3DSurface.ts ShutDownChart");
        }
    };
    var chartInitObj = wasmContext.SCRTRenderLoopManager.implement(chartInitializer);
    var frameRenderer3D = new wasmContext.SCRTFrameRenderer3D();
    chartInitObj.SetFrameRenderer(frameRenderer3D);
    chartInitObj.SetFPSCounterEnabled(false);
    // This may not be used in the case of 3D charts, but we set the property anyway as its passed down to TSR engine when initialising
    chartInitObj.SetImmediateBufferSizeKb(SciChartDefaults_1.SciChartDefaults.wasmBufferSizesKb);
    wasmContext.SCRTSetGlobalRenderLoopManager(chartInitObj);
    // @ts-ignore
    wasmContext.callMain();
};
