"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Tiles
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.acquireImdlParser = acquireImdlParser;
const core_bentley_1 = require("@itwin/core-bentley");
const core_common_1 = require("@itwin/core-common");
const WorkerProxy_1 = require("../../common/WorkerProxy");
const ParseImdlDocument_1 = require("../../common/imdl/ParseImdlDocument");
const IModelApp_1 = require("../../IModelApp");
function acquireImdlParser(args) {
    const timeline = args.timeline;
    if (args.noWorker) {
        return {
            parse: async (options) => (0, ParseImdlDocument_1.parseImdlDocument)({
                ...options,
                timeline,
            }),
            release: () => undefined,
        };
    }
    if (!args.timeline) {
        if (!defaultParser) {
            const worker = (0, WorkerProxy_1.createWorkerProxy)(`${IModelApp_1.IModelApp.publicPath}scripts/parse-imdl-worker.js`);
            defaultParser = {
                parse: async (options) => worker.parse(options, [options.data.buffer]),
                release: () => undefined,
            };
        }
        return defaultParser;
    }
    let parser = parsersWithTimelines.get(args.timeline);
    if (!parser)
        parsersWithTimelines.set(args.timeline, parser = new ParserWithTimeline(args.timeline));
    (0, core_bentley_1.assert)(parser.refCount >= 0);
    ++parser.refCount;
    return parser;
}
let defaultParser;
class ParserWithTimeline {
    refCount = 0;
    _timeline;
    _worker;
    constructor(timeline) {
        this._timeline = timeline;
        this._worker = (0, WorkerProxy_1.createWorkerProxy)(`${IModelApp_1.IModelApp.publicPath}scripts/parse-imdl-worker.js`);
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        this._worker.setTimeline(timeline.toJSON());
    }
    async parse(options) {
        return this._worker.parse(options, [options.data.buffer]);
    }
    release() {
        (0, core_bentley_1.assert)(this.refCount > 0);
        --this.refCount;
        if (this.refCount === 0) {
            parsersWithTimelines.delete(this._timeline);
            this._worker.terminate();
        }
    }
}
const parsersWithTimelines = new core_bentley_1.Dictionary((lhs, rhs) => {
    if (lhs instanceof core_common_1.RenderSchedule.ModelTimeline)
        return rhs instanceof core_common_1.RenderSchedule.ModelTimeline ? lhs.compareTo(rhs) : -1;
    return rhs instanceof core_common_1.RenderSchedule.Script ? lhs.compareTo(rhs) : 1;
});
//# sourceMappingURL=ImdlParser.js.map