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 __());
    };
})();
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 };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { AcCmColor, AcDbBatchProcessing, AcDbBlockTableRecord, AcDbDatabaseConverter, AcDbDimStyleTableRecord, AcDbLayerTableRecord, AcDbLayout, AcDbLinetypeTableRecord, AcDbRasterImageDef, AcDbTextStyleTableRecord, AcDbViewportTableRecord, createWorkerApi, DEFAULT_TEXT_STYLE } from '@mlightcad/data-model';
import { AcDbEntityConverter } from './AcDbEntitiyConverter';
var MODEL_SPACE = '*MODEL_SPACE';
/**
 * Database converter for DWG files based on [libredwg-web](https://github.com/mlight-lee/libredwg-web).
 */
var AcDbLibreDwgConverter = /** @class */ (function (_super) {
    __extends(AcDbLibreDwgConverter, _super);
    function AcDbLibreDwgConverter(config) {
        if (config === void 0) { config = {}; }
        var _this = _super.call(this, config) || this;
        config.useWorker = true;
        if (!config.parserWorkerUrl) {
            config.parserWorkerUrl = '/assets/libredwg-parser-worker.js';
        }
        return _this;
    }
    AcDbLibreDwgConverter.prototype.parse = function (data, timeout) {
        return __awaiter(this, void 0, void 0, function () {
            var effectiveConfig, resolvedTimeout, api, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        effectiveConfig = this.config;
                        resolvedTimeout = this.getParserWorkerTimeout(data, timeout);
                        if (!(effectiveConfig.useWorker && effectiveConfig.parserWorkerUrl)) return [3 /*break*/, 2];
                        api = createWorkerApi({
                            workerUrl: effectiveConfig.parserWorkerUrl,
                            timeout: resolvedTimeout,
                            // One concurrent worker needed for parser
                            maxConcurrentWorkers: 1
                        });
                        return [4 /*yield*/, api.execute(data)
                            // Release worker
                        ];
                    case 1:
                        result = _a.sent();
                        // Release worker
                        api.destroy();
                        if (result.success) {
                            return [2 /*return*/, result.data];
                        }
                        else {
                            throw new Error("Failed to parse drawing due to error: '".concat(result.error, "'"));
                        }
                        return [3 /*break*/, 3];
                    case 2: throw new Error('dwg converter can run in web worker only!');
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Gets all of fonts used by entities in model space and paper space
     * @param dwg dwg database model
     * @returns Returns all of fonts used by entities in model space and paper space
     */
    AcDbLibreDwgConverter.prototype.getFonts = function (dwg) {
        // Build block map. The key is block name.
        var blockMap = new Map();
        dwg.tables.BLOCK_RECORD.entries.forEach(function (btr) {
            blockMap.set(btr.name, btr);
        });
        // Build text style map. The key is text style name, and the value is font name list.
        var styleMap = new Map();
        var getFontName = function (fontFileName) {
            if (fontFileName) {
                var lastDotIndex = fontFileName.lastIndexOf('.');
                if (lastDotIndex >= 0) {
                    return fontFileName.substring(0, lastDotIndex).toLowerCase();
                }
                else {
                    return fontFileName.toLowerCase();
                }
            }
        };
        dwg.tables.STYLE.entries.forEach(function (style) {
            var fontNames = [];
            var fontName = getFontName(style.font);
            if (fontName)
                fontNames.push(fontName);
            fontName = getFontName(style.bigFont);
            if (fontName)
                fontNames.push(fontName);
            styleMap.set(style.name, fontNames);
        });
        var fonts = new Set();
        this.getFontsInBlock(dwg.entities, blockMap, styleMap, fonts);
        return Array.from(fonts);
    };
    /**
     * Iterate entities in model space to get fonts used by text, mtext and insert entities
     */
    AcDbLibreDwgConverter.prototype.getFontsInBlock = function (entities, blockMap, styleMap, fonts) {
        var _this = this;
        var regex = /\\f(.*?)\|/g;
        entities.forEach(function (entity) {
            if (entity.type == 'MTEXT') {
                var mtext = entity;
                __spreadArray([], __read(mtext.text.matchAll(regex)), false).forEach(function (match) {
                    fonts.add(match[1].toLowerCase());
                });
                var fontNames = styleMap.get(mtext.styleName);
                fontNames === null || fontNames === void 0 ? void 0 : fontNames.forEach(function (name) { return fonts.add(name); });
            }
            else if (entity.type == 'TEXT') {
                var text = entity;
                var fontNames = styleMap.get(text.styleName);
                fontNames === null || fontNames === void 0 ? void 0 : fontNames.forEach(function (name) { return fonts.add(name); });
            }
            else if (entity.type == 'INSERT') {
                var insert = entity;
                var block = blockMap.get(insert.name);
                if (block)
                    _this.getFontsInBlock(block.entities, blockMap, styleMap, fonts);
            }
        });
    };
    AcDbLibreDwgConverter.prototype.processLineTypes = function (model, db) {
        var _this = this;
        var lineTypes = model.tables.LTYPE.entries;
        lineTypes.forEach(function (item) {
            var lineType = {
                name: item.name,
                description: item.description,
                standardFlag: item.standardFlag,
                totalPatternLength: item.totalPatternLength,
                pattern: item.pattern
            };
            var record = new AcDbLinetypeTableRecord(lineType);
            _this.processCommonTableEntryAttrs(item, record);
            record.name = item.name;
            db.tables.linetypeTable.add(record);
        });
    };
    AcDbLibreDwgConverter.prototype.processTextStyles = function (model, db) {
        var _this = this;
        var textStyles = model.tables.STYLE.entries;
        textStyles.forEach(function (item) {
            var record = new AcDbTextStyleTableRecord(item);
            _this.processCommonTableEntryAttrs(item, record);
            db.tables.textStyleTable.add(record);
        });
    };
    AcDbLibreDwgConverter.prototype.processDimStyles = function (model, db) {
        var _this = this;
        var dimStyles = model.tables.DIMSTYLE.entries;
        dimStyles.forEach(function (item) {
            var attrs = {
                name: item.name,
                ownerId: item.ownerHandle,
                dimpost: item.DIMPOST || '',
                dimapost: item.DIMAPOST || '',
                dimscale: item.DIMSCALE,
                dimasz: item.DIMASZ,
                dimexo: item.DIMEXO,
                dimdli: item.DIMDLI,
                dimexe: item.DIMEXE,
                dimrnd: item.DIMRND,
                dimdle: item.DIMDLE,
                dimtp: item.DIMTP,
                dimtm: item.DIMTM,
                dimtxt: item.DIMTXT,
                dimcen: item.DIMCEN,
                dimtsz: item.DIMTSZ,
                dimaltf: item.DIMALTF,
                dimlfac: item.DIMLFAC,
                dimtvp: item.DIMTVP,
                dimtfac: item.DIMTFAC,
                dimgap: item.DIMGAP,
                dimaltrnd: item.DIMALTRND,
                dimtol: item.DIMTOL == null || item.DIMTOL == 0 ? 0 : 1,
                dimlim: item.DIMLIM == null || item.DIMLIM == 0 ? 0 : 1,
                dimtih: item.DIMTIH == null || item.DIMTIH == 0 ? 0 : 1,
                dimtoh: item.DIMTOH == null || item.DIMTOH == 0 ? 0 : 1,
                dimse1: item.DIMSE1 == null || item.DIMSE1 == 0 ? 0 : 1,
                dimse2: item.DIMSE2 == null || item.DIMSE2 == 0 ? 0 : 1,
                dimtad: item.DIMTAD,
                dimzin: item.DIMZIN,
                dimazin: item.DIMAZIN,
                dimalt: item.DIMALT,
                dimaltd: item.DIMALTD,
                dimtofl: item.DIMTOFL,
                dimsah: item.DIMSAH,
                dimtix: item.DIMTIX,
                dimsoxd: item.DIMSOXD,
                dimclrd: item.DIMCLRD,
                dimclre: item.DIMCLRE,
                dimclrt: item.DIMCLRT,
                dimadec: item.DIMADEC || 0,
                dimunit: item.DIMUNIT || 2,
                dimdec: item.DIMDEC,
                dimtdec: item.DIMTDEC,
                dimaltu: item.DIMALTU,
                dimalttd: item.DIMALTTD,
                dimaunit: item.DIMAUNIT,
                dimfrac: item.DIMFRAC,
                dimlunit: item.DIMLUNIT,
                dimdsep: item.DIMDSEP,
                dimtmove: item.DIMTMOVE || 0,
                dimjust: item.DIMJUST,
                dimsd1: item.DIMSD1,
                dimsd2: item.DIMSD2,
                dimtolj: item.DIMTOLJ,
                dimtzin: item.DIMTZIN,
                dimaltz: item.DIMALTZ,
                dimalttz: item.DIMALTTZ,
                dimfit: item.DIMFIT || 0,
                dimupt: item.DIMUPT,
                dimatfit: item.DIMATFIT,
                dimtxsty: DEFAULT_TEXT_STYLE, // TODO: Set correct value
                dimldrblk: '', // TODO: Set correct value
                dimblk: item.DIMBLK || '', // TODO: Set correct value
                dimblk1: item.DIMBLK1 || '', // TODO: Set correct value
                dimblk2: item.DIMBLK2 || '', // TODO: Set correct value
                dimlwd: item.DIMLWD,
                dimlwe: item.DIMLWE
            };
            var record = new AcDbDimStyleTableRecord(attrs);
            _this.processCommonTableEntryAttrs(item, record);
            db.tables.dimStyleTable.add(record);
        });
    };
    AcDbLibreDwgConverter.prototype.processLayers = function (model, db) {
        var _this = this;
        var layers = model.tables.LAYER.entries;
        layers.forEach(function (item) {
            var color = new AcCmColor();
            color.colorIndex = item.colorIndex;
            var record = new AcDbLayerTableRecord({
                name: item.name,
                standardFlags: item.standardFlag,
                linetype: item.lineType,
                lineWeight: item.lineweight,
                isOff: item.off,
                color: color,
                isPlottable: item.plotFlag != 0
            });
            _this.processCommonTableEntryAttrs(item, record);
            db.tables.layerTable.add(record);
        });
    };
    AcDbLibreDwgConverter.prototype.processViewports = function (model, db) {
        var _this = this;
        var viewports = model.tables.VPORT.entries;
        viewports.forEach(function (item) {
            var record = new AcDbViewportTableRecord();
            _this.processCommonTableEntryAttrs(item, record);
            if (item.circleSides) {
                record.circleSides = item.circleSides;
            }
            record.standardFlag = item.standardFlag;
            record.center.copy(item.center);
            record.lowerLeftCorner.copy(item.lowerLeftCorner);
            record.upperRightCorner.copy(item.upperRightCorner);
            if (item.snapBasePoint) {
                record.snapBase.copy(item.snapBasePoint);
            }
            if (item.snapRotationAngle) {
                record.snapAngle = item.snapRotationAngle;
            }
            if (item.snapSpacing) {
                record.snapIncrements.copy(item.snapSpacing);
            }
            if (item.majorGridLines) {
                record.gridMajor = item.majorGridLines;
            }
            if (item.gridSpacing) {
                record.gridIncrements.copy(item.gridSpacing);
            }
            if (item.backgroundObjectId) {
                record.backgroundObjectId = item.backgroundObjectId;
            }
            record.gsView.center.copy(item.center);
            record.gsView.viewDirectionFromTarget.copy(item.viewDirectionFromTarget);
            record.gsView.viewTarget.copy(item.viewTarget);
            if (item.lensLength) {
                record.gsView.lensLength = item.lensLength;
            }
            if (item.frontClippingPlane) {
                record.gsView.frontClippingPlane = item.frontClippingPlane;
            }
            if (item.backClippingPlane) {
                record.gsView.backClippingPlane = item.backClippingPlane;
            }
            if (item.viewHeight) {
                record.gsView.viewHeight = item.viewHeight;
            }
            if (item.viewTwistAngle) {
                record.gsView.viewTwistAngle = item.viewTwistAngle;
            }
            if (item.frozenLayers) {
                record.gsView.frozenLayers = item.frozenLayers;
            }
            if (item.styleSheet) {
                record.gsView.styleSheet = item.styleSheet;
            }
            if (item.renderMode) {
                record.gsView.renderMode = item.renderMode;
            }
            if (item.viewMode) {
                record.gsView.viewMode = item.viewMode;
            }
            if (item.ucsIconSetting) {
                record.gsView.ucsIconSetting = item.ucsIconSetting;
            }
            if (item.ucsOrigin) {
                record.gsView.ucsOrigin.copy(item.ucsOrigin);
            }
            if (item.ucsXAxis) {
                record.gsView.ucsXAxis.copy(item.ucsXAxis);
            }
            if (item.ucsYAxis) {
                record.gsView.ucsYAxis.copy(item.ucsYAxis);
            }
            if (item.orthographicType) {
                record.gsView.orthographicType =
                    item.orthographicType;
            }
            if (item.shadePlotSetting) {
                record.gsView.shadePlotSetting = item.shadePlotSetting;
            }
            if (item.shadePlotObjectId) {
                record.gsView.shadePlotObjectId = item.shadePlotObjectId;
            }
            if (item.visualStyleObjectId) {
                record.gsView.visualStyleObjectId = item.visualStyleObjectId;
            }
            if (item.isDefaultLightingOn) {
                record.gsView.isDefaultLightingOn = item.isDefaultLightingOn;
            }
            if (item.defaultLightingType) {
                record.gsView.defaultLightingType =
                    item.defaultLightingType;
            }
            if (item.brightness) {
                record.gsView.brightness = item.brightness;
            }
            if (item.contrast) {
                record.gsView.contrast = item.contrast;
            }
            if (item.ambientColor) {
                record.gsView.ambientColor = item.ambientColor;
            }
            db.tables.viewportTable.add(record);
        });
    };
    AcDbLibreDwgConverter.prototype.processBlockTables = function (model, db) {
        var _this = this;
        var btrs = model.tables.BLOCK_RECORD.entries;
        btrs.forEach(function (btr) {
            var dbBlock = db.tables.blockTable.getAt(btr.name);
            if (!dbBlock) {
                dbBlock = new AcDbBlockTableRecord();
                dbBlock.objectId = btr.handle;
                dbBlock.name = btr.name;
                dbBlock.ownerId = btr.ownerHandle;
                dbBlock.origin.copy(btr.basePoint);
                dbBlock.layoutId = btr.layout;
                db.tables.blockTable.add(dbBlock);
            }
            // Don't process entities in block space until other blocks are processed
            if (!dbBlock.isModelSapce && btr.entities && btr.entities.length > 0) {
                _this.processEntitiesInBlock(btr.entities, dbBlock);
            }
        });
    };
    AcDbLibreDwgConverter.prototype.processBlocks = function (_model, _db) {
        // Do nothing because entities are already processsed in method processBlockTables
    };
    AcDbLibreDwgConverter.prototype.processEntitiesInBlock = function (entities, blockTableRecord) {
        return __awaiter(this, void 0, void 0, function () {
            var converter, entityCount, dbEntities, i, entity, dbEntity;
            return __generator(this, function (_a) {
                converter = new AcDbEntityConverter();
                entityCount = entities.length;
                dbEntities = [];
                for (i = 0; i < entityCount; i++) {
                    entity = entities[i];
                    dbEntity = converter.convert(entity);
                    if (dbEntity) {
                        dbEntities.push(dbEntity);
                    }
                }
                // Use batch append to improve performance
                blockTableRecord.appendEntity(dbEntities);
                return [2 /*return*/];
            });
        });
    };
    /**
     * Breaks up the work into smaller chunks that are executed asynchronously. This is often referred to
     * as "batch processing" or "cooperative multitasking," where the time-consuming task is broken into
     * smaller pieces and executed in small intervals to allow the UI to remain responsive.
     */
    AcDbLibreDwgConverter.prototype.processEntities = function (model, db, minimumChunkSize, startPercentage, progress) {
        return __awaiter(this, void 0, void 0, function () {
            var converter, entities, entityCount, batchProcessor, blockTableRecord;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        converter = new AcDbEntityConverter();
                        entities = [];
                        model.tables.BLOCK_RECORD.entries.forEach(function (btr) {
                            if (_this.isModelSpace(btr.name))
                                entities = btr.entities;
                        });
                        entityCount = entities.length;
                        batchProcessor = new AcDbBatchProcessing(entityCount, 100 - startPercentage.value, minimumChunkSize);
                        // Groups entities by their `type` property and flattens the result into a single array.
                        if (this.config.convertByEntityType) {
                            entities = this.groupAndFlattenByType(entities);
                        }
                        blockTableRecord = db.tables.blockTable.modelSpace;
                        return [4 /*yield*/, batchProcessor.processChunk(function (start, end) { return __awaiter(_this, void 0, void 0, function () {
                                var dbEntities, i, entity, dbEntity, percentage;
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            dbEntities = [];
                                            for (i = start; i < end; i++) {
                                                entity = entities[i];
                                                dbEntity = converter.convert(entity);
                                                if (dbEntity) {
                                                    dbEntities.push(dbEntity);
                                                }
                                            }
                                            // Use batch append to improve performance
                                            blockTableRecord.appendEntity(dbEntities);
                                            if (!progress) return [3 /*break*/, 2];
                                            percentage = startPercentage.value +
                                                (end / entityCount) * (100 - startPercentage.value);
                                            if (percentage > 100)
                                                percentage = 100;
                                            return [4 /*yield*/, progress(percentage, 'ENTITY', 'IN-PROGRESS')];
                                        case 1:
                                            _a.sent();
                                            _a.label = 2;
                                        case 2: return [2 /*return*/];
                                    }
                                });
                            }); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    AcDbLibreDwgConverter.prototype.processHeader = function (model, db) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        var header = model.header;
        // Color index 256 is 'ByLayer'
        if (header.CECOLOR) {
            if (header.CECOLOR.index >= 0 && header.CECOLOR.index <= 256) {
                db.cecolor.colorIndex = header.CECOLOR.index;
            }
            else {
                db.cecolor.setRGBValue(header.CECOLOR.rgb);
            }
        }
        db.angBase = (_a = header.ANGBASE) !== null && _a !== void 0 ? _a : 0;
        db.angDir = (_b = header.ANGDIR) !== null && _b !== void 0 ? _b : 0;
        db.aunits = (_c = header.AUNITS) !== null && _c !== void 0 ? _c : 0;
        db.celtscale = (_d = header.CELTSCALE) !== null && _d !== void 0 ? _d : 1;
        db.ltscale = (_e = header.LTSCALE) !== null && _e !== void 0 ? _e : 1;
        if (header.EXTMAX)
            db.extmax = header.EXTMAX;
        if (header.EXTMIN)
            db.extmin = header.EXTMIN;
        // Initial value of INSUNITS:	1 (imperial) or 4 (metric)
        db.insunits = (_f = header.INSUNITS) !== null && _f !== void 0 ? _f : 1;
        db.pdmode = (_g = header.PDMODE) !== null && _g !== void 0 ? _g : 0;
        db.pdsize = (_h = header.PDSIZE) !== null && _h !== void 0 ? _h : 0.0;
        db.textstyle = (_j = header.TEXTSTYLE) !== null && _j !== void 0 ? _j : DEFAULT_TEXT_STYLE;
    };
    AcDbLibreDwgConverter.prototype.processCommonTableEntryAttrs = function (entry, dbEntry) {
        dbEntry.name = entry.name;
        dbEntry.objectId = entry.handle;
        dbEntry.ownerId = entry.ownerHandle;
    };
    AcDbLibreDwgConverter.prototype.processObjects = function (model, db) {
        this.processLayouts(model, db);
        this.processImageDefs(model, db);
    };
    AcDbLibreDwgConverter.prototype.processLayouts = function (model, db) {
        var _this = this;
        var layoutDict = db.objects.layout;
        var layouts = model.objects.LAYOUT;
        layouts.forEach(function (layout) {
            var e_1, _a;
            var dbLayout = new AcDbLayout();
            dbLayout.layoutName = layout.layoutName;
            dbLayout.tabOrder = layout.tabOrder;
            // layout.paperSpaceTableId doesn't point to the block table record asscicated with
            // this layout. So let's get the assocated block table record id from block table.
            var btrs = db.tables.blockTable.newIterator();
            dbLayout.objectId = layout.handle;
            try {
                for (var btrs_1 = __values(btrs), btrs_1_1 = btrs_1.next(); !btrs_1_1.done; btrs_1_1 = btrs_1.next()) {
                    var btr = btrs_1_1.value;
                    // Because the type of layout id (number) block table record and layout id (BingInt)
                    // in layout dictionary are different, so the converted data are used to compare.
                    // In the future, we will use BigInt type for object id.
                    if (btr.layoutId === dbLayout.objectId) {
                        dbLayout.blockTableRecordId = btr.objectId;
                        break;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (btrs_1_1 && !btrs_1_1.done && (_a = btrs_1.return)) _a.call(btrs_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            // If the layout is not found in the block table due to some unknow reason,
            // let's set the model space block table record id.
            if (!dbLayout.blockTableRecordId) {
                if (layout.layoutName === 'Model') {
                    dbLayout.blockTableRecordId = db.tables.blockTable.modelSpace.objectId;
                }
            }
            dbLayout.limits.min.copy(layout.minLimit);
            dbLayout.limits.max.copy(layout.maxLimit);
            dbLayout.extents.min.copy(layout.minExtent);
            dbLayout.extents.max.copy(layout.maxExtent);
            _this.processCommonObjectAttrs(layout, dbLayout);
            layoutDict.setAt(dbLayout.layoutName, dbLayout);
        });
    };
    AcDbLibreDwgConverter.prototype.processImageDefs = function (model, db) {
        var _this = this;
        var imageDefDict = db.objects.imageDefinition;
        var imageDefs = model.objects.IMAGEDEF;
        imageDefs.forEach(function (imageDef) {
            var dbImageDef = new AcDbRasterImageDef();
            dbImageDef.sourceFileName = imageDef.fileName;
            _this.processCommonObjectAttrs(imageDef, dbImageDef);
            imageDefDict.setAt(dbImageDef.objectId, dbImageDef);
        });
    };
    AcDbLibreDwgConverter.prototype.processCommonObjectAttrs = function (object, dbObject) {
        dbObject.objectId = object.handle;
        dbObject.ownerId = object.ownerHandle;
    };
    /**
     * Groups entities by their `type` property and flattens the result into a single array.
     *
     * The order of `type` groups follows the order in which they first appear in the input array.
     * Items within each group preserve their original order.
     *
     * This runs in O(n) time, which is generally faster than sorting when you
     * don't care about alphabetical order of types.
     *
     * @param entities - The array of entities to group and flatten.
     *
     * @returns A new array of entities grouped by their `type` property.
     */
    AcDbLibreDwgConverter.prototype.groupAndFlattenByType = function (entities) {
        var e_2, _a;
        var groups = {};
        var order = [];
        try {
            for (var entities_1 = __values(entities), entities_1_1 = entities_1.next(); !entities_1_1.done; entities_1_1 = entities_1.next()) {
                var entity = entities_1_1.value;
                if (!groups[entity.type]) {
                    groups[entity.type] = [];
                    order.push(entity.type);
                }
                groups[entity.type].push(entity);
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (entities_1_1 && !entities_1_1.done && (_a = entities_1.return)) _a.call(entities_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
        return order.flatMap(function (type) { return groups[type]; });
    };
    AcDbLibreDwgConverter.prototype.isModelSpace = function (name) {
        return name && name.toUpperCase() == MODEL_SPACE;
    };
    return AcDbLibreDwgConverter;
}(AcDbDatabaseConverter));
export { AcDbLibreDwgConverter };
//# sourceMappingURL=AcDbLibreDwgConverter.js.map