"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PackageType = void 0;
const Constants_1 = require("../core/Constants");
const StorageUtilities_1 = require("../storage/StorageUtilities");
const ZipStorage_1 = require("../storage/ZipStorage");
const Project_1 = require("./Project");
var PackageType;
(function (PackageType) {
    PackageType[PackageType["packSet"] = 0] = "packSet";
    PackageType[PackageType["world"] = 1] = "world";
    PackageType[PackageType["worldTemplate"] = 2] = "worldTemplate";
    PackageType[PackageType["generic"] = 3] = "generic";
    PackageType[PackageType["project"] = 4] = "project";
})(PackageType = exports.PackageType || (exports.PackageType = {}));
class Package {
    storagePath;
    name;
    baseName;
    type;
    file;
    reportFile;
    cacheFolder;
    data;
    get isWorldType() {
        return this.type === PackageType.world || this.type === PackageType.worldTemplate;
    }
    constructor(name, path) {
        this.name = name;
        this.storagePath = path;
        this.baseName = StorageUtilities_1.default.getBaseFromName(name);
        this.type = this._getPackTypeFromPath(path);
    }
    _getPackTypeFromPath(path) {
        const type = StorageUtilities_1.default.getTypeFromName(path);
        switch (type) {
            case "mcworld":
                return PackageType.world;
            case "mcproject":
                return PackageType.project;
            case "mctemplate":
                return PackageType.worldTemplate;
            case "mcaddon":
            case "mcpack":
                return PackageType.packSet;
            default:
                return PackageType.generic;
        }
    }
    async ensureData(carto, file) {
        this.file = file;
        const summaryFile = file.parentFolder.ensureFile(file.name + ".report.html");
        const summaryFileExists = await summaryFile.exists();
        let summaryObject;
        if (summaryFileExists) {
            await summaryFile.loadContent();
            const content = summaryFile.content;
            if (content && typeof content === "string") {
                const adderFunctionDec = content.indexOf("function _addReportJson(");
                let adderFunction = content.indexOf("_addReportJson(");
                if (adderFunction >= 0) {
                    if (adderFunctionDec === adderFunction - 9) {
                        adderFunction = content.indexOf("_addReportJson(", adderFunction + 10);
                    }
                    if (adderFunction >= 0) {
                        const endOfFunction = content.indexOf("</script>", adderFunction);
                        if (endOfFunction > adderFunction) {
                            const previousEnd = content.lastIndexOf(");", endOfFunction);
                            if (previousEnd > adderFunction && previousEnd < endOfFunction) {
                                const jsonContent = content.substring(adderFunction + 15, previousEnd);
                                try {
                                    summaryObject = JSON.parse(jsonContent);
                                }
                                catch (e) { }
                                if (summaryObject) {
                                    this.reportFile = summaryFile;
                                }
                                // if the report was generated by a different version, ignore it and regen a new one.
                                if (summaryObject && summaryObject.generatorVersion !== Constants_1.constants.version) {
                                    summaryObject = undefined;
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!summaryObject) {
            await file.loadContent();
            if (file.content && file.content instanceof Uint8Array) {
                let packRootZipFolder = undefined;
                if (!file.fileContainerStorage) {
                    const zipStorage = new ZipStorage_1.default();
                    zipStorage.storagePath = file.storageRelativePath + "#";
                    await zipStorage.loadFromUint8Array(file.content, file.name);
                    file.fileContainerStorage = zipStorage;
                }
                packRootZipFolder = file.fileContainerStorage.rootFolder;
                const packProject = new Project_1.default(carto, file.name, null);
                packProject.setProjectFolder(packRootZipFolder);
                await packProject.inferProjectItemsFromFiles();
                const pis = packProject.infoSet;
                await pis.generateForProject();
                const hash = await file.getHash();
                const reportHtml = pis.getReportHtml(file.name, file.storageRelativePath, hash);
                summaryFile.setContent(reportHtml);
                await summaryFile.saveContent();
                this.reportFile = summaryFile;
                summaryObject = pis.getDataObject(file.name, file.storageRelativePath, hash);
            }
        }
        if (summaryObject) {
            this.data = summaryObject;
        }
    }
    createReference() {
        const bpRefs = [];
        const rpRefs = [];
        if (this.data && this.data.items) {
            for (let i = 0; i < this.data.items.length; i++) {
                const item = this.data.items[i];
                if (item.gId === "PACK" && item.gIx === 6 && item.d && typeof item.d === "string") {
                    const ref = this.getRefFromString(item.d);
                    if (ref) {
                        bpRefs.push(ref);
                    }
                }
                else if (item.gId === "PACK" && item.gIx === 16 && item.d && typeof item.d === "string") {
                    const ref = this.getRefFromString(item.d);
                    if (ref) {
                        rpRefs.push(ref);
                    }
                }
            }
        }
        const packRef = {
            name: this.name,
            hash: this.data?.sourceHash,
            behaviorPackReferences: bpRefs,
            resourcePackReferences: rpRefs,
        };
        return packRef;
    }
    getRefFromString(uuidPlusVersion) {
        const sections = uuidPlusVersion.split("|");
        if (sections.length !== 2) {
            return undefined;
        }
        const verNumbers = sections[1].split(".");
        if (verNumbers.length !== 3) {
            return undefined;
        }
        const targetVerNumbers = [];
        try {
            targetVerNumbers.push(parseInt(verNumbers[0]));
            targetVerNumbers.push(parseInt(verNumbers[1]));
            targetVerNumbers.push(parseInt(verNumbers[2]));
        }
        catch (e) { }
        if (targetVerNumbers.length !== 3) {
            return undefined;
        }
        return { uuid: sections[0], version: targetVerNumbers };
    }
    matches(packName, isWorldFocused) {
        const packCoreName = this.name.toLowerCase();
        const packBaseName = this.baseName.toLowerCase();
        packName = packName.toLowerCase();
        if ((packBaseName.toLowerCase() === packName &&
            (isWorldFocused === undefined ||
                (isWorldFocused === true && (this.type === PackageType.world || this.type === PackageType.worldTemplate)) ||
                (isWorldFocused === false && this.type !== PackageType.world && this.type !== PackageType.worldTemplate))) ||
            packCoreName === packName) {
            return true;
        }
        return false;
    }
}
exports.default = Package;

//# sourceMappingURL=../maps/app/Package.js.map
