import {  CADFactory, CADFiler, CADObject, Database, DuplicateRecordCloning, Factory, LayerNode, ObjectId, PhysicalMaterialRecord, TextureTableRecord } from "webcad_ue4_api";

// TODO: Danger: 注意入侵性代码
// 疑似是WebCAD中的漏洞，当传入new Database()时，
// Database中的filer.ReadObject方法并不会为CadObject.objectId赋值，
// 导致后续的CadObject.Id.Index发生空指针异常
// 因此需要修改CAD中的Database.AllocationObjectId，尝试手动赋值
// @ts-ignore
Database.prototype.AllocationObjectId = function (this: Database, object: CADObject) {
    if (object.Id === undefined) object.objectId = new ObjectId(undefined, undefined);
    // @ts-ignore
    object.Id.Index = this.idIndex++;
    // @ts-ignore
    this.idMap.set(object.Id.Index, object.Id);
}

export function MaterialOut(material: PhysicalMaterialRecord): string {
    let db = new Database();
    db.WblockCloneObejcts(
        [material],
        db.MaterialTable,
        new Map(),
        DuplicateRecordCloning.Ignore
    );
    let json = JSON.stringify(db.FileWrite().Data);
    // // TODO: Danger: 因为WebCAD依赖库中的部分类的构造函数名异常，所以在生成JSON时需要对类名进行替换
    json = json.replace(LayerNode.name, "LayerNode")
        .replace(TextureTableRecord.name, "TextureTableRecord")
        .replace(PhysicalMaterialRecord.name, "PhysicalMaterialRecord");
    console.debug("DEBUG CAD Object Name", CADFactory['factory'].objectNameMap);
    console.debug("CURRENT PROTOTYPE NAME\n", "LAYERNODE:", LayerNode.name, "TEXTURETABLERECORD:", TextureTableRecord.name, "PHYSICALMATERIALRECORD:", PhysicalMaterialRecord.name);
    return json;
}

export function MaterialIn(fileData: Object[]): PhysicalMaterialRecord
{
    let f = new CADFiler(fileData);
    let db = new Database().FileRead(f);
    db.hm.Enable = false;
    return db.MaterialTable.Symbols.entries().next().value[1];
}