import { AcDbFace as v, AcDbArc as O, AcGeVector3d as D, AcDbCircle as m, AcDbEllipse as k, AcDbLine as F, AcGePoint3d as w, AcDbSpline as T, AcDbPoint as R, AcDbTrace as V, AcDbPolyline as N, AcGePoint2d as b, AcDbPolygonMesh as B, AcDbPolyFaceMesh as z, AcDbPoly2dType as A, AcDb2dPolyline as j, AcDbPoly3dType as y, AcDb3dPolyline as W, AcDbHatch as H, AcGePolyline2d as X, AcGeLine2d as U, AcGeCircArc2d as G, AcGeVector2d as Y, AcGeEllipseArc2d as _, AcGeSpline3d as P, AcGeLoop2d as E, AcDbTable as Z, AcDbText as K, AcDbMText as q, AcDbLeader as J, AcDbAlignedDimension as Q, AcDb3PointAngularDimension as $, AcDbOrdinateDimension as ee, AcDbRadialDimension as ne, AcDbDiametricDimension as oe, AcDbRasterImage as te, AcDbWipeout as se, AcDbViewport as re, AcDbRay as ie, AcDbXline as ce, AcDbAttributeFlags as I, AcDbAttributeMTextFlag as M, AcDbAttribute as le, AcDbAttributeDefinition as ae, AcDbBlockReference as de, AcCmTransparency as pe, AcDbDatabaseConverter as ue, createWorkerApi as fe, AcDbLinetypeTableRecord as he, AcDbTextStyleTableRecord as ge, DEFAULT_TEXT_STYLE as L, AcDbDimStyleTableRecord as De, AcCmColor as Ae, AcDbLayerTableRecord as Ie, AcDbViewportTableRecord as ye, AcDbBlockTableRecord as we, AcDbBatchProcessing as Te, ByLayer as be, AcDbLayout as Pe, AcDbRasterImageDef as Ee } from "@mlightcad/data-model";
class C {
  convert(e) {
    const n = this.createEntity(e);
    return n && this.processCommonAttrs(e, n), n;
  }
  createEntity(e) {
    return e.type == "3DFACE" ? this.convertFace(e) : e.type == "ARC" ? this.convertArc(e) : e.type == "ATTDEF" ? this.convertAttributeDefinition(e) : e.type == "CIRCLE" ? this.convertCirle(e) : e.type == "DIMENSION" ? this.convertDimension(e) : e.type == "ELLIPSE" ? this.convertEllipse(e) : e.type == "HATCH" ? this.convertHatch(e) : e.type == "IMAGE" ? this.convertImage(e) : e.type == "LEADER" ? this.convertLeader(e) : e.type == "LINE" ? this.convertLine(e) : e.type == "LWPOLYLINE" ? this.convertLWPolyline(e) : e.type == "MTEXT" ? this.convertMText(e) : e.type == "POINT" ? this.convertPoint(e) : e.type == "POLYLINE2D" ? this.convertPolyline2d(e) : e.type == "POLYLINE3D" ? this.convertPolyline3d(e) : e.type == "RAY" ? this.convertRay(e) : e.type == "SPLINE" ? this.convertSpline(e) : e.type == "ACAD_TABLE" ? this.convertTable(e) : e.type == "TEXT" ? this.convertText(e) : e.type == "SOLID" ? this.convertSolid(e) : e.type == "VIEWPORT" ? this.convertViewport(e) : e.type == "WIPEOUT" ? this.convertWipeout(e) : e.type == "XLINE" ? this.convertXline(e) : e.type == "INSERT" ? this.convertBlockReference(e) : null;
  }
  convertFace(e) {
    const n = new v();
    return e.corner1 && n.setVertexAt(0, e.corner1), e.corner2 && n.setVertexAt(1, e.corner2), e.corner3 && n.setVertexAt(2, e.corner3), e.corner4 && n.setVertexAt(3, e.corner4), n.setEdgeInvisibilities(e.flag), n;
  }
  convertArc(e) {
    return new O(
      e.center,
      e.radius,
      e.startAngle,
      e.endAngle,
      e.extrusionDirection ?? D.Z_AXIS
    );
  }
  convertCirle(e) {
    return new m(
      e.center,
      e.radius,
      e.extrusionDirection ?? D.Z_AXIS
    );
  }
  convertEllipse(e) {
    const n = new D(e.majorAxisEndPoint), t = n.length();
    return new k(
      e.center,
      e.extrusionDirection ?? D.Z_AXIS,
      n,
      t,
      t * e.axisRatio,
      e.startAngle,
      e.endAngle
    );
  }
  convertLine(e) {
    const n = e.startPoint, t = e.endPoint;
    return new F(
      new w(n.x, n.y, n.z),
      new w(t.x, t.y, t.z)
    );
  }
  convertSpline(e) {
    try {
      if (e.numberOfControlPoints > 0 && e.numberOfKnots > 0)
        return new T(
          e.controlPoints,
          e.knots,
          e.weights,
          e.degree,
          !!(e.flag & 1)
        );
      if (e.numberOfFitPoints > 0)
        return new T(
          e.fitPoints,
          "Uniform",
          e.degree,
          !!(e.flag & 1)
        );
    } catch {
    }
    return null;
  }
  convertPoint(e) {
    const n = new R();
    return n.position = e.position, n;
  }
  convertSolid(e) {
    const n = new V();
    return n.setPointAt(0, { ...e.corner1, z: 0 }), n.setPointAt(1, { ...e.corner2, z: 0 }), n.setPointAt(2, { ...e.corner3, z: 0 }), n.setPointAt(
      3,
      e.corner4 ? { ...e.corner4, z: 0 } : { ...e.corner3, z: 0 }
    ), n.thickness = e.thickness, n;
  }
  convertLWPolyline(e) {
    const n = new N();
    return n.closed = !!(e.flag & 512), e.vertices.forEach((t, o) => {
      n.addVertexAt(
        o,
        new b(t.x, t.y),
        t.bulge,
        t.startWidth,
        t.endWidth
      );
    }), n;
  }
  convertPolyline2d(e) {
    const n = !!(e.flag & 1), t = !!(e.flag & 16), o = !!(e.flag & 64), s = !!(e.flag & 32), r = [], a = [], c = [];
    if (e.vertices.map((i) => {
      if (!(i.flag & 16))
        if (o && i.flag & 128)
          if (i.flag & 64)
            r.push({
              x: i.x,
              y: i.y,
              z: i.z
            }), a.push(i.bulge ?? 0);
          else {
            const d = [];
            i.polyfaceIndex0 != null && i.polyfaceIndex0 != 0 && d.push(Math.abs(i.polyfaceIndex0) - 1), i.polyfaceIndex1 != null && i.polyfaceIndex1 != 0 && d.push(Math.abs(i.polyfaceIndex1) - 1), i.polyfaceIndex2 != null && i.polyfaceIndex2 != 0 && d.push(Math.abs(i.polyfaceIndex2) - 1), i.polyfaceIndex3 != null && i.polyfaceIndex3 != 0 && d.push(Math.abs(i.polyfaceIndex3) - 1), d.length >= 3 && c.push(d);
          }
        else
          r.push({
            x: i.x,
            y: i.y,
            z: i.z
          }), a.push(i.bulge ?? 0);
    }), t) {
      const i = e.meshMVertexCount ?? 2, d = e.meshNVertexCount ?? 2;
      return new B(i, d, r, n, s);
    } else {
      if (o)
        return new z(r, c);
      {
        let i = A.SimplePoly;
        return e.flag & 2 ? i = A.FitCurvePoly : e.flag & 4 && (e.smoothType == 6 ? i = A.CubicSplinePoly : e.smoothType == 5 && (i = A.QuadSplinePoly)), new j(
          i,
          r,
          0,
          n,
          e.startWidth,
          e.endWidth,
          a
        );
      }
    }
  }
  convertPolyline3d(e) {
    const n = !!(e.flag & 1), t = [];
    e.vertices.map((s) => {
      s.flag & 16 || t.push({
        x: s.x,
        y: s.y,
        z: s.z
      });
    });
    let o = y.SimplePoly;
    return e.flag & 4 && (e.smoothType == 6 ? o = y.CubicSplinePoly : e.smoothType == 5 && (o = y.QuadSplinePoly)), new W(o, t, n);
  }
  convertHatch(e) {
    var o;
    const n = new H();
    return (o = e.definitionLines) == null || o.forEach((s) => {
      n.definitionLines.push({
        angle: s.angle,
        base: s.base,
        offset: s.offset,
        dashLengths: s.numberOfDashLengths > 0 ? s.dashLengths : []
      });
    }), n.isSolidFill = e.solidFill == 1, n.hatchStyle = e.hatchStyle, n.patternName = e.patternName, n.patternType = e.patternType, n.patternAngle = e.patternAngle == null ? 0 : e.patternAngle, n.patternScale = e.patternScale == null ? 0 : e.patternScale, e.boundaryPaths.forEach((s) => {
      if (s.boundaryPathTypeFlag & 2) {
        const a = s, c = new X();
        c.closed = a.isClosed, a.vertices.forEach((i, d) => {
          c.addVertexAt(d, {
            x: i.x,
            y: i.y,
            bulge: i.bulge
          });
        }), n.add(c);
      } else {
        const a = s, c = [];
        a.edges.forEach((d) => {
          if (d != null) {
            if (d.type == 1) {
              const l = d;
              c.push(new U(l.start, l.end));
            } else if (d.type == 2) {
              const l = d;
              c.push(
                new G(
                  l.center,
                  l.radius,
                  l.startAngle,
                  l.endAngle,
                  !l.isCCW
                )
              );
            } else if (d.type == 3) {
              const l = d;
              new Y().subVectors(l.end, l.center);
              const p = Math.sqrt(
                Math.pow(l.end.x, 2) + Math.pow(l.end.y, 2)
              ), u = p * l.lengthOfMinorAxis;
              let f = l.startAngle, g = l.endAngle;
              const x = Math.atan2(l.end.y, l.end.x);
              l.isCCW || (f = Math.PI * 2 - f, g = Math.PI * 2 - g), c.push(
                new _(
                  { ...l.center, z: 0 },
                  p,
                  u,
                  f,
                  g,
                  !l.isCCW,
                  x
                )
              );
            } else if (d.type == 4) {
              const l = d;
              if (l.numberOfControlPoints > 0 && l.numberOfKnots > 0) {
                const h = l.controlPoints.map(
                  (f) => ({
                    x: f.x,
                    y: f.y,
                    z: 0
                  })
                );
                let p = !0;
                const u = l.controlPoints.map((f) => (f.weight == null && (p = !1), f.weight || 1));
                c.push(
                  new P(
                    h,
                    l.knots,
                    p ? u : void 0
                  )
                );
              } else if (l.numberOfFitData > 0) {
                const h = l.fitDatum.map((p) => ({
                  x: p.x,
                  y: p.y,
                  z: 0
                }));
                c.push(new P(h, "Uniform"));
              }
            }
          }
        });
        const i = E.buildFromEdges(c);
        i.length == 0 && c.length > 0 ? n.add(new E(c)) : i.forEach((d) => n.add(d));
      }
    }), n;
  }
  convertTable(e) {
    const n = new Z(
      e.name,
      e.rowCount,
      e.columnCount
    );
    return n.tableStyleId = e.tableStyleId, n.owningBlockRecordId = e.blockRecordHandle, e.directionVector && (n.horizontalDirection = new D(e.directionVector)), n.attachmentPoint = e.attachmentPoint, n.position.copy(e.startPoint), n.tableValueFlag = e.tableValue, n.tableOverrideFlag = e.overrideFlag, n.borderColorOverrideFlag = e.borderColorOverrideFlag, n.borderLineweightOverrideFlag = e.borderLineWeightOverrideFlag, n.borderVisibilityOverrideFlag = e.borderVisibilityOverrideFlag, e.columnWidthArr.forEach(
      (t, o) => n.setColumnWidth(o, t)
    ), e.rowHeightArr.forEach(
      (t, o) => n.setRowHeight(o, t)
    ), e.cells.forEach((t, o) => {
      n.setCell(o, t);
    }), n;
  }
  convertText(e) {
    const n = new K();
    return n.textString = e.text, n.styleName = e.styleName, n.height = e.textHeight, n.position.copy(e.startPoint), n.rotation = e.rotation, n.oblique = e.obliqueAngle ?? 0, n.thickness = e.thickness, n.horizontalMode = e.halign, n.verticalMode = e.valign, n.widthFactor = e.xScale ?? 1, n;
  }
  convertMText(e) {
    const n = new q();
    return n.contents = e.text, e.styleName != null && (n.styleName = e.styleName), n.height = e.textHeight, n.width = e.rectWidth, n.rotation = e.rotation || 0, n.location = e.insertionPoint, n.attachmentPoint = e.attachmentPoint, e.direction && (n.direction = new D(e.direction)), n.drawingDirection = e.drawingDirection, n;
  }
  convertLeader(e) {
    const n = new J();
    return e.vertices.forEach((t) => {
      n.appendVertex(t);
    }), n.hasArrowHead = e.isArrowheadEnabled, n.hasHookLine = e.isHooklineExists, n.isSplined = e.isSpline, n.dimensionStyle = e.styleName, n.annoType = e.leaderCreationFlag, n;
  }
  convertDimension(e) {
    if (e.subclassMarker == "AcDbAlignedDimension" || e.subclassMarker == "AcDbRotatedDimension") {
      const n = e, t = new Q(
        n.subDefinitionPoint1,
        n.subDefinitionPoint2,
        n.definitionPoint
      );
      return n.insertionPoint && (t.dimBlockPosition = {
        x: n.insertionPoint.x,
        y: n.insertionPoint.y,
        z: 0
      }), t.rotation = n.rotationAngle, this.processDimensionCommonAttrs(e, t), t;
    } else if (e.subclassMarker == "AcDb3PointAngularDimension") {
      const n = e, t = new $(
        n.centerPoint,
        n.subDefinitionPoint1,
        n.subDefinitionPoint2,
        n.definitionPoint
      );
      return this.processDimensionCommonAttrs(e, t), t;
    } else if (e.subclassMarker == "AcDbOrdinateDimension") {
      const n = e, t = new ee(
        n.subDefinitionPoint1,
        n.subDefinitionPoint2
      );
      return this.processDimensionCommonAttrs(e, t), t;
    } else if (e.subclassMarker == "AcDbRadialDimension") {
      const n = e, t = new ne(
        n.definitionPoint,
        n.centerPoint,
        n.leaderLength
      );
      return this.processDimensionCommonAttrs(e, t), t;
    } else if (e.subclassMarker == "AcDbDiametricDimension") {
      const n = e, t = new oe(
        n.definitionPoint,
        n.centerPoint,
        n.leaderLength
      );
      return this.processDimensionCommonAttrs(e, t), t;
    }
    return null;
  }
  processImage(e, n) {
    n.position.copy(e.position), n.brightness = e.brightness, n.contrast = e.contrast, n.fade = e.fade, n.imageSize.copy(e.imageSize), n.imageDefId = e.imageDefHandle, n.isClipped = e.clipping > 0, n.isShownClipped = (e.flags | 4) > 0, n.isImageShown = (e.flags | 3) > 0, n.isImageTransparent = (e.flags | 8) > 0, e.clippingBoundaryPath.forEach((t) => {
      n.clipBoundary.push(new b(t));
    }), n.clipBoundaryType = e.clippingBoundaryType, n.width = Math.sqrt(
      e.uPixel.x ** 2 + e.uPixel.y ** 2 + e.uPixel.z ** 2
    ) * e.imageSize.x, n.height = Math.sqrt(
      e.vPixel.x ** 2 + e.vPixel.y ** 2 + e.vPixel.z ** 2
    ) * e.imageSize.y, n.rotation = Math.atan2(e.uPixel.y, e.uPixel.x);
  }
  convertImage(e) {
    const n = new te();
    return this.processImage(e, n), n;
  }
  convertWipeout(e) {
    const n = new se();
    return this.processImage(e, n), n;
  }
  convertViewport(e) {
    const n = new re();
    return n.number = e.viewportId, n.centerPoint.copy(e.viewportCenter), n.height = e.height, n.width = e.width, n.viewCenter.copy(e.displayCenter), n.viewHeight = e.viewHeight, n;
  }
  convertRay(e) {
    const n = new ie();
    return n.basePoint.copy(e.firstPoint), n.unitDir.copy(e.unitDirection), n;
  }
  convertXline(e) {
    const n = new ce();
    return n.basePoint.copy(e.firstPoint), n.unitDir.copy(e.unitDirection), n;
  }
  convertAttributeCommon(e, n) {
    const t = e.text;
    n.textString = t.text, n.styleName = t.styleName, n.height = t.textHeight, n.position.copy(t.startPoint), n.rotation = t.rotation, n.oblique = t.obliqueAngle ?? 0, n.thickness = t.thickness, n.horizontalMode = t.halign, n.verticalMode = t.valign, n.widthFactor = t.xScale ?? 1, n.tag = e.tag, n.fieldLength = e.fieldLength, n.isInvisible = (e.flags & I.Invisible) !== 0, n.isConst = (e.flags & I.Const) !== 0, n.isVerifiable = (e.flags & I.Verifiable) !== 0, n.isPreset = (e.flags & I.Preset) !== 0, n.lockPositionInBlock = e.lockPositionFlag, n.isReallyLocked = e.isReallyLocked, n.isMTextAttribute = (e.mtextFlag & M.MultiLine) !== 0, n.isConstMTextAttribute = (e.mtextFlag & M.ConstMultiLine) !== 0;
  }
  convertAttribute(e) {
    const n = new le();
    return this.convertAttributeCommon(e, n), n;
  }
  convertAttributeDefinition(e) {
    const n = new ae();
    return this.convertAttributeCommon(e, n), n.prompt = e.prompt, n;
  }
  convertBlockReference(e) {
    const n = new de(e.name);
    return e.insertionPoint && n.position.copy(e.insertionPoint), n.scaleFactors.x = e.xScale, n.scaleFactors.y = e.yScale, n.scaleFactors.z = e.zScale, n.rotation = e.rotation, n.normal.copy(e.extrusionDirection), e.attribs && e.attribs.forEach((t) => {
      const o = this.convertAttribute(t);
      n.appendAttributes(o);
    }), n;
  }
  processDimensionCommonAttrs(e, n) {
    n.dimBlockId = e.name, n.textPosition.copy(e.textPoint), n.textRotation = e.textRotation || 0, e.textLineSpacingFactor && (n.textLineSpacingFactor = e.textLineSpacingFactor), e.textLineSpacingStyle && (n.textLineSpacingStyle = e.textLineSpacingStyle), n.dimensionStyleName = e.styleName, n.dimensionText = e.text || "", n.measurement = e.measurement;
  }
  processCommonAttrs(e, n) {
    if (n.layer = e.layer || "0", n.objectId = e.handle, n.ownerId = e.ownerBlockRecordSoftId, e.lineType != null && (n.lineType = e.lineType), e.lineweight != null && (n.lineWeight = e.lineweight), e.lineTypeScale != null && (n.linetypeScale = e.lineTypeScale), e.color != null && n.color.setRGBValue(e.color), e.colorIndex != null && (n.color.colorIndex = e.colorIndex), e.colorName && (n.color.colorName = e.colorName), e.isVisible != null && (n.visibility = e.isVisible), e.transparency != null) {
      const t = new pe();
      t.method = e.transparencyType, (t.isByBlock || t.isByBlock) && (t.alpha = e.transparency), n.transparency = t;
    }
  }
}
const Me = "*MODEL_SPACE";
class Ce extends ue {
  constructor(e = {}) {
    super(e), e.useWorker = !0, e.parserWorkerUrl || (e.parserWorkerUrl = "/assets/libredwg-parser-worker.js");
  }
  async parse(e, n) {
    const t = this.config, o = this.getParserWorkerTimeout(e, n);
    if (t.useWorker && t.parserWorkerUrl) {
      const s = fe({
        workerUrl: t.parserWorkerUrl,
        timeout: o,
        maxConcurrentWorkers: 1
      }), r = await s.execute(e);
      if (s.destroy(), r.success)
        return r.data;
      throw new Error(
        `Failed to parse drawing due to error: '${r.error}'`
      );
    } else
      throw new Error("dwg converter can run in web worker only!");
  }
  getFonts(e) {
    const n = /* @__PURE__ */ new Map();
    e.tables.BLOCK_RECORD.entries.forEach((r) => {
      n.set(r.name, r);
    });
    const t = /* @__PURE__ */ new Map(), o = (r) => {
      if (r) {
        const a = r.lastIndexOf(".");
        return a >= 0 ? r.substring(0, a).toLowerCase() : r.toLowerCase();
      }
    };
    e.tables.STYLE.entries.forEach((r) => {
      const a = [];
      let c = o(r.font);
      c && a.push(c), c = o(r.bigFont), c && a.push(c), t.set(r.name, a);
    });
    const s = /* @__PURE__ */ new Set();
    return this.getFontsInBlock(e.entities, n, t, s), Array.from(s);
  }
  getFontsInBlock(e, n, t, o) {
    const s = /\\f(.*?)\|/g;
    e.forEach((r) => {
      if (r.type == "MTEXT") {
        const a = r;
        [...a.text.matchAll(s)].forEach((i) => {
          o.add(i[1].toLowerCase());
        });
        const c = t.get(a.styleName);
        c == null || c.forEach((i) => o.add(i));
      } else if (r.type == "TEXT") {
        const a = r, c = t.get(a.styleName);
        c == null || c.forEach((i) => o.add(i));
      } else if (r.type == "INSERT") {
        const a = r, c = n.get(a.name);
        c && this.getFontsInBlock(c.entities, n, t, o);
      }
    });
  }
  processLineTypes(e, n) {
    e.tables.LTYPE.entries.forEach((o) => {
      const s = {
        name: o.name,
        description: o.description,
        standardFlag: o.standardFlag,
        totalPatternLength: o.totalPatternLength,
        pattern: o.pattern
      }, r = new he(s);
      this.processCommonTableEntryAttrs(o, r), r.name = o.name, n.tables.linetypeTable.add(r);
    });
  }
  processTextStyles(e, n) {
    e.tables.STYLE.entries.forEach((o) => {
      const s = new ge(o);
      this.processCommonTableEntryAttrs(o, s), n.tables.textStyleTable.add(s);
    });
  }
  processDimStyles(e, n) {
    e.tables.DIMSTYLE.entries.forEach((o) => {
      const s = {
        name: o.name,
        ownerId: o.ownerHandle,
        dimpost: o.DIMPOST || "",
        dimapost: o.DIMAPOST || "",
        dimscale: o.DIMSCALE,
        dimasz: o.DIMASZ,
        dimexo: o.DIMEXO,
        dimdli: o.DIMDLI,
        dimexe: o.DIMEXE,
        dimrnd: o.DIMRND,
        dimdle: o.DIMDLE,
        dimtp: o.DIMTP,
        dimtm: o.DIMTM,
        dimtxt: o.DIMTXT,
        dimcen: o.DIMCEN,
        dimtsz: o.DIMTSZ,
        dimaltf: o.DIMALTF,
        dimlfac: o.DIMLFAC,
        dimtvp: o.DIMTVP,
        dimtfac: o.DIMTFAC,
        dimgap: o.DIMGAP,
        dimaltrnd: o.DIMALTRND,
        dimtol: o.DIMTOL == null || o.DIMTOL == 0 ? 0 : 1,
        dimlim: o.DIMLIM == null || o.DIMLIM == 0 ? 0 : 1,
        dimtih: o.DIMTIH == null || o.DIMTIH == 0 ? 0 : 1,
        dimtoh: o.DIMTOH == null || o.DIMTOH == 0 ? 0 : 1,
        dimse1: o.DIMSE1 == null || o.DIMSE1 == 0 ? 0 : 1,
        dimse2: o.DIMSE2 == null || o.DIMSE2 == 0 ? 0 : 1,
        dimtad: o.DIMTAD,
        dimzin: o.DIMZIN,
        dimazin: o.DIMAZIN,
        dimalt: o.DIMALT,
        dimaltd: o.DIMALTD,
        dimtofl: o.DIMTOFL,
        dimsah: o.DIMSAH,
        dimtix: o.DIMTIX,
        dimsoxd: o.DIMSOXD,
        dimclrd: o.DIMCLRD,
        dimclre: o.DIMCLRE,
        dimclrt: o.DIMCLRT,
        dimadec: o.DIMADEC || 0,
        dimunit: o.DIMUNIT || 2,
        dimdec: o.DIMDEC,
        dimtdec: o.DIMTDEC,
        dimaltu: o.DIMALTU,
        dimalttd: o.DIMALTTD,
        dimaunit: o.DIMAUNIT,
        dimfrac: o.DIMFRAC,
        dimlunit: o.DIMLUNIT,
        dimdsep: o.DIMDSEP || ".",
        dimtmove: o.DIMTMOVE || 0,
        dimjust: o.DIMJUST,
        dimsd1: o.DIMSD1,
        dimsd2: o.DIMSD2,
        dimtolj: o.DIMTOLJ,
        dimtzin: o.DIMTZIN,
        dimaltz: o.DIMALTZ,
        dimalttz: o.DIMALTTZ,
        dimfit: o.DIMFIT || 0,
        dimupt: o.DIMUPT,
        dimatfit: o.DIMATFIT,
        dimtxsty: L,
        dimldrblk: "",
        dimblk: o.DIMBLK || "",
        dimblk1: o.DIMBLK1 || "",
        dimblk2: o.DIMBLK2 || "",
        dimlwd: o.DIMLWD,
        dimlwe: o.DIMLWE
      }, r = new De(s);
      this.processCommonTableEntryAttrs(o, r), n.tables.dimStyleTable.add(r);
    });
  }
  processLayers(e, n) {
    e.tables.LAYER.entries.forEach((o) => {
      const s = new Ae();
      s.colorIndex = o.colorIndex;
      const r = new Ie({
        name: o.name,
        standardFlags: o.standardFlag,
        linetype: o.lineType,
        lineWeight: o.lineweight,
        isOff: o.off,
        color: s,
        isPlottable: o.plotFlag != 0
      });
      this.processCommonTableEntryAttrs(o, r), n.tables.layerTable.add(r);
    });
  }
  processViewports(e, n) {
    e.tables.VPORT.entries.forEach((o) => {
      const s = new ye();
      this.processCommonTableEntryAttrs(o, s), o.circleSides && (s.circleSides = o.circleSides), s.standardFlag = o.standardFlag, s.center.copy(o.center), s.lowerLeftCorner.copy(o.lowerLeftCorner), s.upperRightCorner.copy(o.upperRightCorner), o.snapBasePoint && s.snapBase.copy(o.snapBasePoint), o.snapRotationAngle && (s.snapAngle = o.snapRotationAngle), o.snapSpacing && s.snapIncrements.copy(o.snapSpacing), o.majorGridLines && (s.gridMajor = o.majorGridLines), o.gridSpacing && s.gridIncrements.copy(o.gridSpacing), o.backgroundObjectId && (s.backgroundObjectId = o.backgroundObjectId), s.gsView.center.copy(o.center), s.gsView.viewDirectionFromTarget.copy(o.viewDirectionFromTarget), s.gsView.viewTarget.copy(o.viewTarget), o.lensLength && (s.gsView.lensLength = o.lensLength), o.frontClippingPlane && (s.gsView.frontClippingPlane = o.frontClippingPlane), o.backClippingPlane && (s.gsView.backClippingPlane = o.backClippingPlane), o.viewHeight && (s.gsView.viewHeight = o.viewHeight), o.viewTwistAngle && (s.gsView.viewTwistAngle = o.viewTwistAngle), o.frozenLayers && (s.gsView.frozenLayers = o.frozenLayers), o.styleSheet && (s.gsView.styleSheet = o.styleSheet), o.renderMode && (s.gsView.renderMode = o.renderMode), o.viewMode && (s.gsView.viewMode = o.viewMode), o.ucsIconSetting && (s.gsView.ucsIconSetting = o.ucsIconSetting), o.ucsOrigin && s.gsView.ucsOrigin.copy(o.ucsOrigin), o.ucsXAxis && s.gsView.ucsXAxis.copy(o.ucsXAxis), o.ucsYAxis && s.gsView.ucsYAxis.copy(o.ucsYAxis), o.orthographicType && (s.gsView.orthographicType = o.orthographicType), o.shadePlotSetting && (s.gsView.shadePlotSetting = o.shadePlotSetting), o.shadePlotObjectId && (s.gsView.shadePlotObjectId = o.shadePlotObjectId), o.visualStyleObjectId && (s.gsView.visualStyleObjectId = o.visualStyleObjectId), o.isDefaultLightingOn && (s.gsView.isDefaultLightingOn = o.isDefaultLightingOn), o.defaultLightingType && (s.gsView.defaultLightingType = o.defaultLightingType), o.brightness && (s.gsView.brightness = o.brightness), o.contrast && (s.gsView.contrast = o.contrast), o.ambientColor && (s.gsView.ambientColor = o.ambientColor), n.tables.viewportTable.add(s);
    });
  }
  processBlockTables(e, n) {
    e.tables.BLOCK_RECORD.entries.forEach((o) => {
      let s = n.tables.blockTable.getAt(o.name);
      s || (s = new we(), s.objectId = o.handle, s.name = o.name, s.ownerId = o.ownerHandle, s.origin.copy(o.basePoint), s.layoutId = o.layout, s.blockInsertUnits = o.insertionUnits, s.explodability = o.explodability, s.blockScaling = o.scalability, o.bmpPreview && (s.bmpPreview = o.bmpPreview), n.tables.blockTable.add(s)), !s.isModelSapce && o.entities && o.entities.length > 0 && this.processEntitiesInBlock(o.entities, s);
    });
  }
  processBlocks(e, n) {
  }
  async processEntitiesInBlock(e, n) {
    const t = new C(), o = e.length, s = [];
    for (let r = 0; r < o; r++) {
      const a = e[r], c = t.convert(a);
      c && s.push(c);
    }
    n.appendEntity(s);
  }
  async processEntities(e, n, t, o, s) {
    const r = new C();
    let a = [];
    e.tables.BLOCK_RECORD.entries.forEach((l) => {
      this.isModelSpace(l.name) && (a = l.entities);
    });
    const c = a.length, i = new Te(
      c,
      100 - o.value,
      t
    );
    this.config.convertByEntityType && (a = this.groupAndFlattenByType(a));
    const d = n.tables.blockTable.modelSpace;
    await i.processChunk(async (l, h) => {
      const p = [];
      for (let u = l; u < h; u++) {
        const f = a[u], g = r.convert(f);
        g && p.push(g);
      }
      if (d.appendEntity(p), s) {
        let u = o.value + h / c * (100 - o.value);
        u > 100 && (u = 100), await s(u, "ENTITY", "IN-PROGRESS");
      }
    });
  }
  processHeader(e, n) {
    const t = e.header;
    t.CECOLOR && (t.CECOLOR.index >= 0 && t.CECOLOR.index <= 256 ? n.cecolor.colorIndex = t.CECOLOR.index : n.cecolor.setRGBValue(t.CECOLOR.rgb)), n.angBase = t.ANGBASE ?? 0, n.angDir = t.ANGDIR ?? 0, n.aunits = t.AUNITS ?? 0, n.celtype = t.CELTYPE ?? be, n.celtscale = t.CELTSCALE ?? 1, n.ltscale = t.LTSCALE ?? 1, t.EXTMAX && (n.extmax = t.EXTMAX), t.EXTMIN && (n.extmin = t.EXTMIN), n.insunits = t.INSUNITS ?? 1, n.pdmode = t.PDMODE ?? 0, n.pdsize = t.PDSIZE ?? 0, n.textstyle = t.TEXTSTYLE ?? L;
  }
  processCommonTableEntryAttrs(e, n) {
    n.name = e.name, n.objectId = e.handle, n.ownerId = e.ownerHandle;
  }
  processObjects(e, n) {
    this.processLayouts(e, n), this.processImageDefs(e, n);
  }
  processLayouts(e, n) {
    const t = n.objects.layout;
    e.objects.LAYOUT.forEach((s) => {
      const r = new Pe();
      r.layoutName = s.layoutName, r.tabOrder = s.tabOrder;
      const a = n.tables.blockTable.newIterator();
      r.objectId = s.handle;
      for (const c of a)
        if (c.layoutId === r.objectId) {
          r.blockTableRecordId = c.objectId;
          break;
        }
      r.blockTableRecordId || s.layoutName === "Model" && (r.blockTableRecordId = n.tables.blockTable.modelSpace.objectId), r.limits.min.copy(s.minLimit), r.limits.max.copy(s.maxLimit), r.extents.min.copy(s.minExtent), r.extents.max.copy(s.maxExtent), s.viewportId && r.viewportArray.push(s.viewportId), this.processCommonObjectAttrs(s, r), t.setAt(r.layoutName, r);
    });
  }
  processImageDefs(e, n) {
    const t = n.objects.imageDefinition;
    e.objects.IMAGEDEF.forEach((s) => {
      const r = new Ee();
      r.sourceFileName = s.fileName, this.processCommonObjectAttrs(s, r), t.setAt(r.objectId, r);
    });
  }
  processCommonObjectAttrs(e, n) {
    n.objectId = e.handle, n.ownerId = e.ownerHandle;
  }
  groupAndFlattenByType(e) {
    const n = {}, t = [];
    for (const o of e)
      n[o.type] || (n[o.type] = [], t.push(o.type)), n[o.type].push(o);
    return t.flatMap((o) => n[o]);
  }
  isModelSpace(e) {
    return e && e.toUpperCase() == Me;
  }
}
export {
  Ce as AcDbLibreDwgConverter
};
