"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 ManagedComponent_1 = require("./ManagedComponent");
const StorageUtilities_1 = require("../storage/StorageUtilities");
const Database_1 = require("./Database");
const MinecraftUtilities_1 = require("./MinecraftUtilities");
const IProjectItemData_1 = require("../app/IProjectItemData");
const AttachableResourceDefinition_1 = require("./AttachableResourceDefinition");
const TypeScriptDefinition_1 = require("./TypeScriptDefinition");
const Utilities_1 = require("../core/Utilities");
class ItemTypeDefinition {
    wrapper = null;
    _behaviorPackFile;
    _id;
    _isLoaded = false;
    _managed = {};
    _data;
    _onLoaded = new ste_events_1.EventDispatcher();
    _onComponentAdded = new ste_events_1.EventDispatcher();
    _onComponentRemoved = new ste_events_1.EventDispatcher();
    _onComponentChanged = new ste_events_1.EventDispatcher();
    get data() {
        return this._data;
    }
    get onComponentAdded() {
        return this._onComponentAdded.asEvent();
    }
    get onComponentRemoved() {
        return this._onComponentRemoved.asEvent();
    }
    get onComponentChanged() {
        return this._onComponentChanged.asEvent();
    }
    get isLoaded() {
        return this._isLoaded;
    }
    get behaviorPackFile() {
        return this._behaviorPackFile;
    }
    get onLoaded() {
        return this._onLoaded.asEvent();
    }
    set behaviorPackFile(newFile) {
        this._behaviorPackFile = newFile;
    }
    get id() {
        if (this._id === undefined) {
            return "";
        }
        return this._id;
    }
    set id(newId) {
        this._id = newId;
    }
    get shortId() {
        if (this._id !== undefined) {
            if (this._id.startsWith("minecraft:")) {
                return this._id.substring(10, this._id.length);
            }
            return this._id;
        }
        return undefined;
    }
    async getFormatVersionIsCurrent() {
        const fv = this.getFormatVersion();
        if (fv === undefined || fv.length !== 3) {
            return false;
        }
        return await Database_1.default.isRecentVersionFromVersionArray(fv);
    }
    getFormatVersion() {
        if (!this.wrapper) {
            return undefined;
        }
        return MinecraftUtilities_1.default.getVersionArrayFrom(this.wrapper.format_version);
    }
    ensureComponent(id, defaultData) {
        const comp = this.getComponent(id);
        if (comp) {
            return comp;
        }
        return this.addComponent(id, defaultData);
    }
    getComponent(id) {
        if (!this._data || !this._data.components) {
            return undefined;
        }
        if (!Utilities_1.default.isUsableAsObjectKey(id)) {
            Log_1.default.unsupportedToken(id);
            throw new Error();
        }
        if (!this._managed[id]) {
            const comp = this._data.components[id];
            if (comp) {
                this._managed[id] = new ManagedComponent_1.ManagedComponent(this._data.components, id, comp);
            }
        }
        return this._managed[id];
    }
    notifyComponentUpdated(id) {
        const component = this.getComponent(id);
        if (component === undefined) {
            Log_1.default.unexpectedUndefined("ITNCU");
        }
        else {
            this._onComponentChanged.dispatch(this, component);
        }
    }
    getAllComponents() {
        return this.getComponents();
    }
    getCustomComponentIds() {
        let customComponentIds = [];
        const customComponent = this.getComponent("minecraft:custom_components");
        if (customComponent) {
            let compData = customComponent.getData();
            if (compData && Array.isArray(compData)) {
                for (const str of compData) {
                    if (typeof str === "string") {
                        customComponentIds.push(str);
                    }
                }
            }
        }
        return customComponentIds;
    }
    getComponents() {
        const componentSet = [];
        if (this._data !== undefined) {
            for (const componentName in this._data.components) {
                const component = this.getComponent(componentName);
                if (component !== undefined) {
                    componentSet.push(component);
                }
            }
        }
        return componentSet;
    }
    async addChildItems(project, item) {
        const itemsCopy = project.getItemsCopy();
        let customComponentIds = this.getCustomComponentIds();
        for (const candItem of itemsCopy) {
            if (candItem.itemType === IProjectItemData_1.ProjectItemType.ts) {
                await candItem.ensureStorage();
                if (candItem.primaryFile) {
                    await candItem.load();
                    const tsd = await TypeScriptDefinition_1.default.ensureOnFile(candItem.primaryFile);
                    if (tsd && tsd.data && customComponentIds) {
                        let doAddTs = false;
                        for (const customCompId of customComponentIds) {
                            if (tsd.data.indexOf(customCompId) >= 0) {
                                doAddTs = true;
                                break;
                            }
                        }
                        if (doAddTs) {
                            item.addChildItem(candItem);
                        }
                    }
                }
            }
            else if (candItem.itemType === IProjectItemData_1.ProjectItemType.attachableResourceJson) {
                await candItem.ensureStorage();
                if (candItem.primaryFile) {
                    const ard = await AttachableResourceDefinition_1.default.ensureOnFile(candItem.primaryFile);
                    if (ard) {
                        const id = ard.id;
                        if (id === this.id) {
                            item.addChildItem(candItem);
                        }
                    }
                }
            }
        }
    }
    setBehaviorPackFormatVersion(versionStr) {
        this._ensureBehaviorPackDataInitialized();
        if (this.wrapper) {
            this.wrapper.format_version = versionStr;
        }
    }
    addComponent(id, componentOrData) {
        this._ensureBehaviorPackDataInitialized();
        const bpData = this._data;
        const mc = componentOrData instanceof ManagedComponent_1.ManagedComponent
            ? componentOrData
            : new ManagedComponent_1.ManagedComponent(bpData.components, id, componentOrData);
        bpData.components[id] = mc.getData();
        this._managed[id] = mc;
        this._onComponentAdded.dispatch(this, mc);
        return mc;
    }
    removeComponent(id) {
        if (this._data === undefined) {
            return;
        }
        const newBehaviorPacks = {};
        const newManagedComponents = {};
        for (const name in this._data.components) {
            if (name !== id) {
                const component = this._data.components[name];
                newBehaviorPacks[name] = component;
            }
        }
        for (const name in this._managed) {
            if (name !== id) {
                newManagedComponents[name] = this._managed[name];
            }
        }
        this._data.components = newBehaviorPacks;
        this._managed = newManagedComponents;
    }
    _ensureBehaviorPackDataInitialized() {
        if (this._data === undefined) {
            this._data = {
                description: {
                    identifier: "unknown",
                },
                components: {},
                events: {},
            };
        }
    }
    static async ensureOnFile(file, loadHandler) {
        let itt;
        if (file.manager === undefined) {
            itt = new ItemTypeDefinition();
            itt.behaviorPackFile = file;
            file.manager = itt;
        }
        if (file.manager !== undefined && file.manager instanceof ItemTypeDefinition) {
            itt = file.manager;
            if (!itt.isLoaded && loadHandler) {
                itt.onLoaded.subscribe(loadHandler);
            }
            await itt.load();
        }
        return itt;
    }
    static isVisualComponent(value) {
        if (value === "minecraft:icon" ||
            value === "minecraft:display_name" ||
            value === "minecraft:glint" ||
            value === "minecraft:hover_text_color") {
            return true;
        }
        return false;
    }
    persist() {
        if (this._behaviorPackFile === undefined) {
            return;
        }
        const bpString = JSON.stringify(this.wrapper, null, 2);
        this._behaviorPackFile.setContent(bpString);
    }
    async load() {
        if (this._behaviorPackFile === undefined || this._isLoaded) {
            return;
        }
        await this._behaviorPackFile.loadContent();
        if (this._behaviorPackFile.content === null || this._behaviorPackFile.content instanceof Uint8Array) {
            return;
        }
        this.wrapper = StorageUtilities_1.default.getJsonObject(this._behaviorPackFile);
        if (this.wrapper) {
            const item = this.wrapper["minecraft:item"];
            if (item && item.description) {
                this.id = item.description.identifier;
            }
            this._data = item;
        }
        this._isLoaded = true;
    }
}
exports.default = ItemTypeDefinition;

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