"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 Utilities_1 = require("../core/Utilities");
const Database_1 = require("./Database");
const TextureDefinition_1 = require("./TextureDefinition");
class JsonUIResourceDefinition {
    jsonUIScreen;
    _file;
    _isLoaded = false;
    _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 namespaceId() {
        if (!this.jsonUIScreen || !this.jsonUIScreen["namespace"]) {
            return undefined;
        }
        return this.jsonUIScreen["namespace"];
    }
    static async ensureOnFile(file, loadHandler) {
        let et;
        if (file.manager === undefined) {
            et = new JsonUIResourceDefinition();
            et.file = file;
            file.manager = et;
        }
        if (file.manager !== undefined && file.manager instanceof JsonUIResourceDefinition) {
            et = file.manager;
            if (!et.isLoaded) {
                if (loadHandler) {
                    et.onLoaded.subscribe(loadHandler);
                }
                await et.load();
            }
        }
        return et;
    }
    persist() {
        if (this._file === undefined) {
            return;
        }
        if (!this.jsonUIScreen) {
            Log_1.default.unexpectedUndefined("ITRDP");
            return;
        }
        const defString = JSON.stringify(this.jsonUIScreen, null, 2);
        this._file.setContent(defString);
    }
    getControlRefs() {
        const namespaceId = this.namespaceId;
        const jsonUITextureRefs = [];
        if (namespaceId && this.jsonUIScreen) {
            for (const jsonControlId in this.jsonUIScreen) {
                const jsonControl = this.jsonUIScreen[jsonControlId];
                if (jsonControlId !== "namespace" && jsonControl && jsonControl.texture) {
                    if (!jsonUITextureRefs.includes(jsonControlId)) {
                        jsonUITextureRefs.push(jsonControlId);
                    }
                }
            }
        }
        return jsonUITextureRefs;
    }
    getTexturePaths() {
        const texturePaths = [];
        if (this.jsonUIScreen) {
            this.addTexturesFromArrayOfKeyPaths([this.jsonUIScreen], texturePaths);
        }
        return texturePaths;
    }
    addTexturesFromArrayOfKeyPaths(controlSets, texturePaths) {
        for (const controlSet of controlSets) {
            for (const key in controlSet) {
                const control = controlSet[key];
                if (key !== "namespace" && key !== "controls") {
                    if (typeof control === "string") {
                        texturePaths.push(control);
                    }
                    else {
                        if (control.texture) {
                            const tex = TextureDefinition_1.default.canonicalizeTexturePath(control.texture);
                            if (tex) {
                                texturePaths.push(tex);
                            }
                        }
                        if (control.controls) {
                            this.addTexturesFromArrayOfKeyPaths(control.controls, texturePaths);
                        }
                    }
                }
            }
        }
    }
    async load() {
        if (this._isLoaded) {
            return;
        }
        if (this._file === undefined) {
            Log_1.default.unexpectedUndefined("PERPF");
            return;
        }
        if (!this._file.isContentLoaded) {
            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.jsonUIScreen = data;
        this._isLoaded = true;
        this._onLoaded.dispatch(this, this);
    }
    getPackRootFolder() {
        let packRootFolder = undefined;
        if (this.file && this.file.parentFolder) {
            let parentFolder = this.file.parentFolder;
            packRootFolder = StorageUtilities_1.default.getParentOfParentFolderNamed("ui", 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.getTexturePaths();
        if (textureList.length > 0) {
            for (const candItem of itemsCopy) {
                if ((candItem.itemType === IProjectItemData_1.ProjectItemType.texture || candItem.itemType === IProjectItemData_1.ProjectItemType.uiTexture) &&
                    packRootFolder &&
                    textureList) {
                    if (!candItem.isContentLoaded) {
                        await candItem.loadContent();
                    }
                    if (candItem.primaryFile) {
                        let relativePath = TextureDefinition_1.default.canonicalizeTexturePath(this.getRelativePath(candItem.primaryFile, packRootFolder));
                        if (relativePath) {
                            if (textureList && textureList.includes(relativePath)) {
                                item.addChildItem(candItem);
                                textureList = Utilities_1.default.removeItemInArray(relativePath, textureList);
                            }
                        }
                    }
                }
            }
            if (textureList) {
                for (const texturePath of textureList) {
                    if (!texturePath.startsWith("$")) {
                        const isVanilla = await Database_1.default.isVanillaToken(texturePath);
                        item.addUnfulfilledRelationship(texturePath, IProjectItemData_1.ProjectItemType.texture, isVanilla);
                    }
                }
            }
        }
    }
}
exports.default = JsonUIResourceDefinition;

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