"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", { value: true });
const Log_1 = require("../core/Log");
const ste_events_1 = require("ste-events");
const StorageUtilities_1 = require("../storage/StorageUtilities");
const IProjectItemData_1 = require("../app/IProjectItemData");
const ModelGeometryDefinition_1 = require("./ModelGeometryDefinition");
class EntityTypeResourceDefinition {
    constructor() {
        this._isLoaded = false;
        this._onLoaded = new ste_events_1.EventDispatcher();
    }
    get isLoaded() {
        return this._isLoaded;
    }
    get file() {
        return this._file;
    }
    get onLoaded() {
        return this._onLoaded.asEvent();
    }
    set file(newFile) {
        this._file = newFile;
    }
    get id() {
        if (!this._data) {
            return undefined;
        }
        return this._data.identifier;
    }
    get textures() {
        if (!this._data) {
            return undefined;
        }
        return this._data.textures;
    }
    get texturesList() {
        if (!this._data || !this._data.textures) {
            return undefined;
        }
        const textureList = [];
        for (const key in this._data.textures) {
            const texturePath = this._data.textures[key];
            if (texturePath) {
                textureList.push(texturePath);
            }
        }
        return textureList;
    }
    get geometry() {
        if (!this._data) {
            return undefined;
        }
        return this._data.geometry;
    }
    get geometryList() {
        if (!this._data || !this._data.geometry) {
            return undefined;
        }
        const geometryList = [];
        for (const key in this._data.geometry) {
            const geometryPath = this._data.geometry[key];
            if (geometryPath) {
                geometryList.push(geometryPath);
            }
        }
        return geometryList;
    }
    getTextureItems(entityTypeResourceProjectItem) {
        if (!this._data || !this._data.geometry || !entityTypeResourceProjectItem.childItems) {
            return undefined;
        }
        const results = {};
        for (const key in this._data.textures) {
            let texturePath = this._data.textures[key];
            if (texturePath) {
                texturePath = StorageUtilities_1.default.canonicalizePath(texturePath);
                for (const projectItemRel of entityTypeResourceProjectItem.childItems) {
                    if (projectItemRel.childItem.itemType === IProjectItemData_1.ProjectItemType.texture && projectItemRel.childItem.projectPath) {
                        let texturePathCand = StorageUtilities_1.default.canonicalizePath(projectItemRel.childItem.projectPath);
                        const lastPeriod = texturePathCand.lastIndexOf(".");
                        if (lastPeriod >= 0) {
                            texturePathCand = texturePathCand.substring(0, lastPeriod).toLowerCase();
                        }
                        if (texturePathCand.endsWith(texturePath)) {
                            results[key] = projectItemRel.childItem;
                        }
                    }
                }
            }
        }
        return results;
    }
    getFormatVersion() {
        if (!this._dataWrapper) {
            return undefined;
        }
        const fv = this._dataWrapper.format_version;
        if (typeof fv === "number") {
            return [fv];
        }
        if (typeof fv === "string") {
            let fvarr = this._dataWrapper.format_version.split(".");
            let fvarrInt = [];
            for (let i = 0; i < fvarr.length; i++) {
                try {
                    fvarrInt.push(parseInt(fvarr[i]));
                }
                catch (e) { }
            }
            return fvarrInt;
        }
        return undefined;
    }
    get formatVersion() {
        if (!this._dataWrapper || !this._dataWrapper.format_version) {
            return undefined;
        }
        return this._dataWrapper.format_version;
    }
    static async ensureOnFile(file, loadHandler) {
        let et;
        if (file.manager === undefined) {
            et = new EntityTypeResourceDefinition();
            et.file = file;
            file.manager = et;
        }
        if (file.manager !== undefined && file.manager instanceof EntityTypeResourceDefinition) {
            et = file.manager;
            if (!et.isLoaded && loadHandler) {
                et.onLoaded.subscribe(loadHandler);
            }
            await et.load();
        }
        return et;
    }
    persist() {
        if (this._file === undefined) {
            return;
        }
        const defString = JSON.stringify(this._dataWrapper, null, 2);
        this._file.setContent(defString);
    }
    async load() {
        if (this._isLoaded) {
            return;
        }
        if (this._file === undefined) {
            Log_1.default.unexpectedUndefined("ETRPF");
            return;
        }
        await this._file.loadContent();
        if (!this._file.content || this._file.content instanceof Uint8Array) {
            return;
        }
        let data = {};
        let result = StorageUtilities_1.default.getJsonObject(this._file);
        if (result) {
            data = result;
        }
        this._dataWrapper = data;
        if (this._dataWrapper && this._dataWrapper["minecraft:client_entity"]) {
            this._data = this._dataWrapper["minecraft:client_entity"].description;
        }
        this._isLoaded = true;
        this._onLoaded.dispatch(this, this);
    }
    async addChildItems(project, item) {
        const itemsCopy = project.getItemsCopy();
        let packRootFolder = undefined;
        if (this.file && this.file.parentFolder) {
            let parentFolder = this.file.parentFolder;
            while (parentFolder.name !== "entity" && parentFolder.parentFolder) {
                parentFolder = parentFolder.parentFolder;
            }
            if (parentFolder.parentFolder) {
                packRootFolder = parentFolder.parentFolder;
            }
        }
        const textureList = this.texturesList;
        const geometryList = this.geometryList;
        for (const candItem of itemsCopy) {
            if (candItem.itemType === IProjectItemData_1.ProjectItemType.texture && packRootFolder && textureList) {
                await candItem.ensureStorage();
                if (candItem.file) {
                    let relativePath = candItem.file.getFolderRelativePath(packRootFolder);
                    if (relativePath) {
                        const lastPeriod = relativePath?.lastIndexOf(".");
                        if (lastPeriod >= 0) {
                            relativePath = relativePath?.substring(0, lastPeriod).toLowerCase();
                        }
                        relativePath = StorageUtilities_1.default.ensureNotStartsWithDelimiter(relativePath);
                        if (this.texturesList?.includes(relativePath)) {
                            item.addChildItem(candItem);
                        }
                    }
                }
            }
            else if (candItem.itemType === IProjectItemData_1.ProjectItemType.modelGeometryJson && geometryList) {
                await candItem.ensureStorage();
                if (candItem.file) {
                    const model = await ModelGeometryDefinition_1.default.ensureOnFile(candItem.file);
                    if (model) {
                        let doAddModel = false;
                        for (const modelId of model.identifiers) {
                            if (this.geometryList?.includes(modelId)) {
                                doAddModel = true;
                            }
                        }
                        if (doAddModel) {
                            item.addChildItem(candItem);
                        }
                    }
                }
            }
        }
    }
}
exports.default = EntityTypeResourceDefinition;

//# sourceMappingURL=../maps/minecraft/EntityTypeResourceDefinition.js.map
