"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.ImdlReader = void 0;
exports.readElementGraphics = readElementGraphics;
exports.readImdlContent = readImdlContent;
const core_bentley_1 = require("@itwin/core-bentley");
const core_geometry_1 = require("@itwin/core-geometry");
const core_common_1 = require("@itwin/core-common");
const IModelApp_1 = require("../IModelApp");
const GraphicBranch_1 = require("../render/GraphicBranch");
const ParseImdlDocument_1 = require("../common/imdl/ParseImdlDocument");
const internal_1 = require("./internal");
/** Convert the byte array returned by [[TileAdmin.requestElementGraphics]] into a [[RenderGraphic]].
 * @param bytes The binary graphics data obtained from `requestElementGraphics`.
 * @param iModel The iModel with which the graphics are associated.
 * @param modelId The Id of the [[GeometricModelState]] with which the graphics are associated. Can be an invalid Id.
 * @param is3d True if the graphics are 3d.
 * @param options Options customizing how [Feature]($common)s within the graphic can be resymbolized; or false if you don't want to produce a batch.
 * @public
 * @extensions
 */
async function readElementGraphics(bytes, iModel, modelId, is3d, options) {
    const stream = core_bentley_1.ByteStream.fromUint8Array(bytes);
    const reader = ImdlReader.create({
        stream, iModel, modelId, is3d, options,
        system: IModelApp_1.IModelApp.renderSystem,
    });
    const result = await reader.read();
    return result.graphic;
}
/** @internal */
async function readImdlContent(args) {
    const isCanceled = args.isCanceled ?? (() => false);
    let content;
    try {
        content = (0, core_common_1.decodeTileContentDescription)({
            stream: args.stream,
            sizeMultiplier: args.sizeMultiplier,
            is2d: !args.is3d,
            options: IModelApp_1.IModelApp.tileAdmin,
            isVolumeClassifier: core_common_1.BatchType.VolumeClassifier === args.type,
            isLeaf: args.isLeaf,
        });
    }
    catch (e) {
        if (e instanceof core_common_1.TileReadError)
            return { isLeaf: true, readStatus: e.errorNumber };
        else
            throw e;
    }
    args.stream.reset();
    const parseOpts = {
        data: args.stream.readBytes(0, args.stream.length),
        batchModelId: args.modelId,
        is3d: args.is3d,
        maxVertexTableSize: IModelApp_1.IModelApp.renderSystem.maxTextureSize,
        omitEdges: false === args.loadEdges,
        createUntransformedRootNode: args.containsTransformNodes,
        modelGroups: args.modelGroups,
    };
    const document = args.parseDocument ? (await args.parseDocument(parseOpts)) : await (0, ParseImdlDocument_1.parseImdlDocument)({ ...parseOpts, timeline: args.timeline });
    if (isCanceled())
        return { isLeaf: true, readStatus: core_common_1.TileReadStatus.Canceled };
    else if (typeof document === "number")
        return { isLeaf: true, readStatus: document };
    let graphic = await (0, internal_1.decodeImdlGraphics)({
        system: args.system,
        iModel: args.iModel,
        document,
        isCanceled: args.isCanceled,
        tileData: args.tileData,
    });
    if (isCanceled())
        return { isLeaf: true, readStatus: core_common_1.TileReadStatus.Canceled };
    if (graphic && false !== args.options) {
        const featureTable = (0, ParseImdlDocument_1.convertFeatureTable)(document.featureTable, args.modelId);
        graphic = args.system.createBatch(graphic, featureTable, content.contentRange, args.options);
    }
    if (graphic && document.rtcCenter) {
        const rtcBranch = new GraphicBranch_1.GraphicBranch(true);
        rtcBranch.add(graphic);
        graphic = args.system.createBranch(rtcBranch, core_geometry_1.Transform.createTranslation(core_geometry_1.Point3d.fromJSON(document.rtcCenter)));
    }
    return {
        readStatus: core_common_1.TileReadStatus.Success,
        isLeaf: content.isLeaf,
        sizeMultiplier: content.sizeMultiplier,
        contentRange: content.contentRange.isNull ? undefined : content.contentRange,
        graphic,
        emptySubRangeMask: content.emptySubRangeMask,
    };
}
/** @internal */
var ImdlReader;
(function (ImdlReader) {
    function create(args) {
        return {
            read: async () => readImdlContent(args),
        };
    }
    ImdlReader.create = create;
})(ImdlReader || (exports.ImdlReader = ImdlReader = {}));
//# sourceMappingURL=ImdlReader.js.map