"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", { value: true });
const ste_events_1 = require("ste-events");
const Utilities_1 = require("../core/Utilities");
const StorageUtilities_1 = require("../storage/StorageUtilities");
const IProjectItemData_1 = require("../app/IProjectItemData");
const BehaviorManifestDefinition_1 = require("./BehaviorManifestDefinition");
const MinecraftUtilities_1 = require("./MinecraftUtilities");
const Log_1 = require("../core/Log");
class ResourceManifestDefinition {
    _file;
    _id;
    _isLoaded = false;
    definition;
    _onLoaded = new ste_events_1.EventDispatcher();
    get isLoaded() {
        return this._isLoaded;
    }
    get file() {
        return this._file;
    }
    set file(newFile) {
        this._file = newFile;
    }
    get onLoaded() {
        return this._onLoaded.asEvent();
    }
    get description() {
        if (!this.definition || !this.definition.header) {
            return undefined;
        }
        return this.definition.header.description;
    }
    set description(newDescription) {
        if (this.definition && this.definition.header && newDescription) {
            this.definition.header.description = newDescription;
        }
    }
    get packScope() {
        if (!this.definition || !this.definition.header) {
            return undefined;
        }
        return this.definition.header.pack_scope;
    }
    set packScope(newValue) {
        if (!this.definition || !this.definition.header) {
            return;
        }
        this.definition.header.pack_scope = newValue;
    }
    get productType() {
        if (!this.definition || !this.definition.metadata) {
            return undefined;
        }
        return this.definition.metadata.product_type;
    }
    set productType(value) {
        this.ensureMetadata();
        if (!this.definition || !this.definition.metadata) {
            return;
        }
        this.definition.metadata.product_type = value;
    }
    get subpacks() {
        if (!this.definition || !this.definition.subpacks) {
            return undefined;
        }
        return this.definition.subpacks;
    }
    get capabilities() {
        if (!this.definition || !this.definition.capabilities) {
            return undefined;
        }
        return this.definition.capabilities;
    }
    get version() {
        if (!this.definition || !this.definition.header || !this.definition.header.version) {
            return undefined;
        }
        return this.definition.header.version;
    }
    get dependencies() {
        if (!this.definition || !this.definition.dependencies) {
            return undefined;
        }
        return this.definition.dependencies;
    }
    get name() {
        if (this.definition && this.definition.header) {
            return this.definition.header.name;
        }
        return undefined;
    }
    set name(newName) {
        if (this.definition && this.definition.header && newName) {
            this.definition.header.name = newName;
        }
    }
    get id() {
        if (this.definition && this.definition.header) {
            return this.definition.header.uuid;
        }
        return this._id;
    }
    set id(newId) {
        if (this.definition && this.definition.header && newId) {
            this.definition.header.uuid = newId;
        }
        this._id = newId;
    }
    async setUuid(newId, project) {
        const oldUuid = this.id;
        this.id = newId;
        if (newId && oldUuid && project) {
            await ResourceManifestDefinition.setNewResourcePackId(project, newId, oldUuid);
        }
    }
    ensureHeaderForProject(project) {
        return this.ensureHeader(project.title, project.description);
    }
    get minEngineVersion() {
        if (!this.definition || !this.definition.header || !this.definition.header.min_engine_version) {
            return undefined;
        }
        return this.definition.header.min_engine_version;
    }
    setMinEngineVersion(versionArray, project) {
        const header = this.ensureHeaderForProject(project);
        header.min_engine_version = versionArray;
    }
    static async setNewResourcePackId(project, newResourcePackId, oldResourcePackId) {
        const itemsCopy = project.getItemsCopy();
        let setResourcePack = false;
        for (let i = 0; i < itemsCopy.length; i++) {
            const pi = itemsCopy[i];
            if (pi.primaryFile) {
                if (pi.itemType === IProjectItemData_1.ProjectItemType.resourcePackManifestJson && !setResourcePack) {
                    const rpManifestJson = await ResourceManifestDefinition.ensureOnFile(pi.primaryFile);
                    if (rpManifestJson) {
                        if (rpManifestJson.id && Utilities_1.default.uuidEqual(rpManifestJson.id, oldResourcePackId)) {
                            rpManifestJson.id = newResourcePackId;
                            setResourcePack = true;
                            await rpManifestJson.save();
                        }
                        else if (rpManifestJson.definition && rpManifestJson.definition.dependencies) {
                            const deps = rpManifestJson.definition?.dependencies;
                            for (const dep of deps) {
                                if (dep.uuid === oldResourcePackId) {
                                    dep.uuid = newResourcePackId;
                                }
                            }
                            await rpManifestJson.save();
                        }
                    }
                }
                else if (pi.itemType === IProjectItemData_1.ProjectItemType.behaviorPackManifestJson) {
                    const bpManifestJson = await BehaviorManifestDefinition_1.default.ensureOnFile(pi.primaryFile);
                    if (bpManifestJson) {
                        if (bpManifestJson.definition && bpManifestJson.definition.dependencies) {
                            const deps = bpManifestJson.definition?.dependencies;
                            for (const dep of deps) {
                                if (dep.uuid === oldResourcePackId) {
                                    dep.uuid = newResourcePackId;
                                }
                            }
                            await bpManifestJson.save();
                        }
                    }
                }
            }
        }
    }
    hasAddonProperties() {
        return this.productType === "addon" && this.packScope === "world";
    }
    async setAddonProperties() {
        this.productType = "addon";
        this.packScope = "world";
        await this.save();
    }
    randomizeModuleUuids(newDataModuleId, oldDataModuleId) {
        if (!this.definition) {
            return;
        }
        for (let i = 0; i < this.definition.modules.length; i++) {
            const mod = this.definition.modules[i];
            if (mod.uuid) {
                if (oldDataModuleId && newDataModuleId && (mod.uuid === oldDataModuleId || mod.uuid === newDataModuleId)) {
                    mod.uuid = newDataModuleId;
                }
                else {
                    mod.uuid = Utilities_1.default.createUuid();
                }
            }
        }
    }
    static async ensureOnFile(file, loadHandler) {
        let rmj;
        if (file.manager === undefined) {
            rmj = new ResourceManifestDefinition();
            rmj.file = file;
            file.manager = rmj;
        }
        if (file.manager !== undefined && file.manager instanceof ResourceManifestDefinition) {
            rmj = file.manager;
            if (!rmj.isLoaded) {
                if (loadHandler) {
                    rmj.onLoaded.subscribe(loadHandler);
                }
                await rmj.load();
            }
        }
        return rmj;
    }
    persist() {
        if (this._file === undefined) {
            return;
        }
        if (!this.definition) {
            Log_1.default.unexpectedUndefined("RMDP");
            return;
        }
        const pjString = JSON.stringify(this.definition, null, 2);
        this._file.setContent(pjString);
    }
    ensureDefinition(name, description) {
        if (!this.definition) {
            this.definition = {
                format_version: 2,
                header: {
                    name: name,
                    description: description,
                    version: [0, 0, 1],
                    min_engine_version: [1, 20, 10],
                    uuid: Utilities_1.default.createUuid(),
                },
                modules: [],
                dependencies: [],
            };
        }
    }
    getSubpackByFolderName(folderName) {
        if (!this.definition) {
            return undefined;
        }
        if (!this.definition.subpacks) {
            return undefined;
        }
        for (const subpack of this.definition.subpacks) {
            if (subpack.folder_name === folderName) {
                return subpack;
            }
        }
        return undefined;
    }
    ensureHeader(name, description) {
        this.ensureDefinition(name, description);
        if (!this.definition) {
            throw new Error();
        }
        if (!this.definition.header) {
            this.definition.header = this.getDefaultHeader(name, description);
        }
        return this.definition.header;
    }
    ensureMetadata() {
        if (!this.definition) {
            return undefined;
        }
        if (!this.definition.metadata) {
            this.definition.metadata = {};
        }
        return this.definition.metadata;
    }
    ensureGeneratedWith(toolName, versionString) {
        const metadata = this.ensureMetadata();
        if (!metadata) {
            return undefined;
        }
        if (!metadata.generated_with) {
            metadata.generated_with = {};
        }
        if (!metadata.generated_with[toolName]) {
            metadata.generated_with[toolName] = [];
        }
        if (!metadata.generated_with[toolName].includes(versionString)) {
            metadata.generated_with[toolName].push(versionString);
        }
    }
    getDefaultHeader(name, description) {
        return {
            name: name,
            description: description,
            version: [0, 0, 1],
            min_engine_version: [1, 20, 10],
            uuid: Utilities_1.default.createUuid(),
        };
    }
    async save() {
        if (this._file === undefined) {
            return;
        }
        this.persist();
        await this._file.saveContent(false);
    }
    async load() {
        if (this._file === undefined || this._isLoaded) {
            return;
        }
        if (!this._file.isContentLoaded) {
            await this._file.loadContent();
        }
        if (this._file.content === null || this._file.content instanceof Uint8Array) {
            return;
        }
        this.definition = StorageUtilities_1.default.getJsonObject(this._file);
        this._isLoaded = true;
    }
    static validatePackReferenceVersion(version) {
        if (!version) {
            return {
                isValid: false,
                errorMessage: "Missing version",
            };
        }
        // Use MinecraftUtilities to parse version
        const versionArray = MinecraftUtilities_1.default.getVersionArrayFrom(version);
        if (!versionArray ||
            versionArray.length !== 3 ||
            !versionArray.every((v) => typeof v === "number" && v >= 0)) {
            return {
                isValid: false,
                errorMessage: "Invalid version format. Expected valid version string or array of 3 non-negative numbers",
            };
        }
        return {
            isValid: true,
            versionArray: versionArray,
        };
    }
}
exports.default = ResourceManifestDefinition;

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