"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 AnimationResourceDefinition_1 = require("./AnimationResourceDefinition");
const RenderControllerSetDefinition_1 = require("./RenderControllerSetDefinition");
const Utilities_1 = require("../core/Utilities");
const ModelGeometryDefinition_1 = require("./ModelGeometryDefinition");
const Database_1 = require("./Database");
const MinecraftDefinitions_1 = require("./MinecraftDefinitions");
class AttachableResourceDefinition {
    constructor() {
        this._isLoaded = false;
        this._onLoaded = new ste_events_1.EventDispatcher();
    }
    get isLoaded() {
        return this._isLoaded;
    }
    get file() {
        return this._file;
    }
    get data() {
        return this._data;
    }
    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;
        }
        if (this._data.textures === undefined) {
            this._data.textures = {};
        }
        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.toLowerCase());
            }
        }
        return textureList;
    }
    get texturesIdList() {
        if (!this._data || !this._data.textures) {
            return undefined;
        }
        const textureIdList = [];
        for (const key in this._data.textures) {
            textureIdList.push(key);
        }
        return textureIdList;
    }
    get renderControllerIdList() {
        if (!this._data || !this._data.render_controllers) {
            return undefined;
        }
        return this._data.render_controllers;
    }
    get animationIdList() {
        if (!this._data || !this._data.animations) {
            return undefined;
        }
        const animationIdList = [];
        for (const key in this._data.animations) {
            animationIdList.push(key);
        }
        return animationIdList;
    }
    get animationList() {
        if (!this._data || !this._data.animations) {
            return undefined;
        }
        const animationList = [];
        for (const key in this._data.animations) {
            const val = this._data.animations[key];
            if (val) {
                animationList.push(val);
            }
        }
        return animationList;
    }
    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 attachable;
        if (file.manager === undefined) {
            attachable = new AttachableResourceDefinition();
            attachable.file = file;
            file.manager = attachable;
        }
        if (file.manager !== undefined && file.manager instanceof AttachableResourceDefinition) {
            attachable = file.manager;
            if (!attachable.isLoaded && loadHandler) {
                attachable.onLoaded.subscribe(loadHandler);
            }
            await attachable.load();
        }
        return attachable;
    }
    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("ATTRPF");
            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:attachable"]) {
            this._data = this._dataWrapper["minecraft:attachable"].description;
        }
        this._isLoaded = true;
        this._onLoaded.dispatch(this, this);
    }
    async deleteLinkToChild(rel) {
        let packRootFolder = this.getPackRootFolder();
        if (this._data === undefined) {
            await this.load();
        }
        const etrChildItems = rel.parentItem.childItems;
        if (rel.childItem.itemType === IProjectItemData_1.ProjectItemType.texture && this._data && this._data.textures) {
            await rel.childItem.ensureStorage();
            if (rel.childItem.file && packRootFolder) {
                let relativePath = this.getRelativePath(rel.childItem.file, packRootFolder);
                if (relativePath) {
                    for (const key in this._data.textures) {
                        const texturePath = this._data.textures[key];
                        if (texturePath === relativePath) {
                            this._data.textures[key] = undefined;
                            if (etrChildItems) {
                                for (const otherChild of etrChildItems) {
                                    if (otherChild.childItem.itemType === IProjectItemData_1.ProjectItemType.renderControllerJson) {
                                        const renderController = (await MinecraftDefinitions_1.default.get(otherChild.childItem));
                                        renderController.removeTexture(key);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        this.persist();
    }
    getPackRootFolder() {
        let packRootFolder = undefined;
        if (this.file && this.file.parentFolder) {
            let parentFolder = this.file.parentFolder;
            while (parentFolder.name !== "attachables" && parentFolder.parentFolder) {
                parentFolder = parentFolder.parentFolder;
            }
            if (parentFolder.parentFolder) {
                packRootFolder = parentFolder.parentFolder;
            }
        }
        return packRootFolder;
    }
    getRelativePath(file, packRootFolder) {
        let relativePath = file.getFolderRelativePath(packRootFolder);
        if (relativePath) {
            const lastPeriod = relativePath?.lastIndexOf(".");
            if (lastPeriod >= 0) {
                relativePath = relativePath?.substring(0, lastPeriod).toLowerCase();
            }
            relativePath = StorageUtilities_1.default.ensureNotStartsWithDelimiter(relativePath);
        }
        return relativePath;
    }
    async addChildItems(project, item) {
        const itemsCopy = project.getItemsCopy();
        let packRootFolder = this.getPackRootFolder();
        let textureList = this.texturesList;
        let geometryList = this.geometryList;
        let renderControllerIdList = this.renderControllerIdList;
        let animationIdList = this.animationIdList;
        for (const candItem of itemsCopy) {
            if (candItem.itemType === IProjectItemData_1.ProjectItemType.animationResourceJson && animationIdList) {
                await candItem.ensureStorage();
                if (candItem.file) {
                    const animationDef = await AnimationResourceDefinition_1.default.ensureOnFile(candItem.file);
                    const animIds = animationDef?.idList;
                    if (animIds) {
                        for (const animId of animationIdList) {
                            if (animIds.includes(animId)) {
                                item.addChildItem(candItem);
                                continue;
                            }
                        }
                    }
                }
            }
            else if (candItem.itemType === IProjectItemData_1.ProjectItemType.renderControllerJson && renderControllerIdList) {
                await candItem.ensureStorage();
                if (candItem.file) {
                    const renderControllerDef = await RenderControllerSetDefinition_1.default.ensureOnFile(candItem.file);
                    const renderIds = renderControllerDef?.idList;
                    if (renderIds) {
                        for (const rcId of renderControllerIdList) {
                            if (renderIds.includes(rcId)) {
                                item.addChildItem(candItem);
                                continue;
                            }
                        }
                    }
                }
            }
            else if (candItem.itemType === IProjectItemData_1.ProjectItemType.texture && packRootFolder && textureList) {
                await candItem.ensureStorage();
                if (candItem.file) {
                    let relativePath = this.getRelativePath(candItem.file, packRootFolder);
                    if (relativePath) {
                        if (textureList && textureList.includes(relativePath)) {
                            item.addChildItem(candItem);
                            textureList = Utilities_1.default.removeItemInArray(relativePath, textureList);
                        }
                    }
                }
            }
            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 (geometryList && geometryList.includes(modelId)) {
                                doAddModel = true;
                                geometryList = Utilities_1.default.removeItemInArray(modelId, geometryList);
                            }
                        }
                        if (doAddModel) {
                            item.addChildItem(candItem);
                        }
                    }
                }
            }
        }
        if (textureList) {
            for (const texturePath of textureList) {
                item.addUnfulfilledRelationship(texturePath, IProjectItemData_1.ProjectItemType.texture, await Database_1.default.isVanillaToken(texturePath));
            }
        }
        if (geometryList) {
            for (const geoId of geometryList) {
                item.addUnfulfilledRelationship(geoId, IProjectItemData_1.ProjectItemType.modelGeometryJson, await Database_1.default.isVanillaToken(geoId));
            }
        }
    }
}
exports.default = AttachableResourceDefinition;

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