"use strict";
/* ---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
// some code copied and modified from https://github.com/microsoft/vscode/blob/d5277e8e2b73134126cabd4fe570a15b821e96c1/src/vs/workbench/api/common/extHostLocalizationService.ts
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtHostLocalization = void 0;
exports.createLocalizationApiFactory = createLocalizationApiFactory;
const ide_core_common_1 = require("@opensumi/ide-core-common");
const strings_1 = require("@opensumi/ide-utils/lib/strings");
const vscode_1 = require("../../../common/vscode");
class ExtHostLocalization {
    constructor(rpcProtocol, logger) {
        this.rpcProtocol = rpcProtocol;
        this.logger = logger;
        this.bundleCache = new Map();
        this.whenReadyDeferred = new ide_core_common_1.Deferred();
        this.proxy = this.rpcProtocol.getProxy(vscode_1.MainThreadAPIIdentifier.MainThreadLocalization);
        this.isDefaultLanguage = this.currentLanguage === ide_core_common_1.LANGUAGE_DEFAULT;
    }
    get whenReady() {
        return this.whenReadyDeferred.promise;
    }
    $setCurrentLanguage(language) {
        this.currentLanguage = language;
        this.whenReadyDeferred.resolve();
    }
    getMessage(extensionId, details) {
        var _a;
        const { message, args, comment } = details;
        if (this.isDefaultLanguage) {
            return (0, strings_1.format2)(message, args !== null && args !== void 0 ? args : {});
        }
        let key = message;
        if (comment && comment.length > 0) {
            key += `/${Array.isArray(comment) ? comment.join('') : comment}`;
        }
        const str = (_a = this.bundleCache.get(extensionId)) === null || _a === void 0 ? void 0 : _a.contents[key];
        if (!str) {
            this.logger.warn(`Using default string since no string found in i18n bundle that has the key: ${key}`);
        }
        return (0, strings_1.format2)(str !== null && str !== void 0 ? str : message, args !== null && args !== void 0 ? args : {});
    }
    getBundle(extensionId) {
        var _a;
        return (_a = this.bundleCache.get(extensionId)) === null || _a === void 0 ? void 0 : _a.contents;
    }
    getBundleUri(extensionId) {
        var _a;
        return (_a = this.bundleCache.get(extensionId)) === null || _a === void 0 ? void 0 : _a.uri;
    }
    async initializeLocalizedMessages(extension) {
        var _a;
        await this.whenReady;
        if (this.isDefaultLanguage || (!extension.l10n && !extension.isBuiltin)) {
            return;
        }
        if (this.bundleCache.has(extension.identifier.value)) {
            return;
        }
        let contents;
        const locatization = await this.getBundleLocation(extension);
        if (!locatization.uri) {
            this.logger.warn(`No bundle location found for extension ${extension.identifier.value}`);
            return;
        }
        try {
            const response = await this.proxy.$fetchBundleContents(locatization.uri);
            const result = JSON.parse(response);
            // 'contents.bundle' is a well-known key in the language pack json file that contains the _code_ translations for the extension
            contents = locatization.fromBundle ? (_a = result.contents) === null || _a === void 0 ? void 0 : _a.bundle : result;
        }
        catch (e) {
            this.logger.error(`Failed to load translations for ${extension.identifier.value} from ${locatization.uri}: ${e.message}`);
            return;
        }
        if (contents) {
            this.bundleCache.set(extension.identifier.value, {
                contents,
                uri: locatization.uri,
            });
        }
    }
    async getBundleLocation(extension) {
        // VS Code 中，对于内置插件会默认从语言包内尝试获取 i18n 文件内容
        // 由于内置的逻辑存在差异，这里对于每个插件都尝试获取一下，以便兼容性
        // 见：https://github.com/microsoft/vscode/blob/d5277e8e2b73134126cabd4fe570a15b821e96c1/src/vs/workbench/api/common/extHostLocalizationService.ts#L97
        const uri = await this.proxy.$fetchBuiltInBundleUri(extension.identifier.value, this.currentLanguage);
        if (uri) {
            return {
                fromBundle: true,
                uri,
            };
        }
        return {
            fromBundle: false,
            uri: extension.l10n
                ? ide_core_common_1.Uri.file(ide_core_common_1.path.join(extension.extensionLocation.fsPath.toString(), extension.l10n, `bundle.l10n.${this.currentLanguage}.json`))
                : undefined,
        };
    }
}
exports.ExtHostLocalization = ExtHostLocalization;
function createLocalizationApiFactory(extHostLocalization, extension) {
    return {
        t(...params) {
            if (typeof params[0] === 'string') {
                const key = params.shift();
                // We have either rest args which are Array<string | number | boolean> or an array with a single Record<string, any>.
                // This ensures we get a Record<string | number, any> which will be formatted correctly.
                const argsFormatted = !params || typeof params[0] !== 'object' ? params : params[0];
                return extHostLocalization.getMessage(extension.identifier.value, {
                    message: key,
                    args: argsFormatted,
                });
            }
            return extHostLocalization.getMessage(extension.identifier.value, params[0]);
        },
        get bundle() {
            return extHostLocalization.getBundle(extension.identifier.value);
        },
        get uri() {
            return extHostLocalization.getBundleUri(extension.identifier.value);
        },
    };
}
//# sourceMappingURL=ext.host.localization.js.map