"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalizationsContributionPoint = void 0;
const tslib_1 = require("tslib");
const di_1 = require("@opensumi/di");
const ide_core_browser_1 = require("@opensumi/ide-core-browser");
const ide_core_common_1 = require("@opensumi/ide-core-common");
const ide_extension_storage_1 = require("@opensumi/ide-extension-storage");
const common_1 = require("@opensumi/ide-file-service/lib/common");
const common_2 = require("../../../common");
const types_1 = require("../../types");
const { Path } = ide_core_browser_1.path;
let LocalizationsContributionPoint = class LocalizationsContributionPoint extends common_2.VSCodeContributePoint {
    constructor() {
        super(...arguments);
        this._whenContributed = new ide_core_common_1.Deferred();
    }
    get whenContributed() {
        return this._whenContributed.promise;
    }
    safeParseJSON(content) {
        let json;
        try {
            json = (0, ide_core_browser_1.parseWithComments)(content);
            return json;
        }
        catch (error) {
            return this.logger.error(`Language configuration file parsing error, ${error.stack}`);
        }
    }
    async contribute() {
        try {
            const promises = [];
            const currentLanguage = this.preferenceService.get(ide_core_browser_1.GeneralSettingsId.Language) || (0, ide_core_browser_1.getLanguageId)();
            const currentExtensions = this.extensionManageService.getExtensionInstances();
            for (const contrib of this.contributesMap) {
                const { extensionId, contributes } = contrib;
                const extension = this.extensionManageService.getExtensionInstanceByExtId(extensionId);
                for await (const localization of contributes) {
                    if (localization.translations) {
                        const languageId = normalizeLanguageId(localization.languageId);
                        if (languageId !== (0, ide_core_browser_1.getLanguageId)()) {
                            continue;
                        }
                        promises.push(...localization.translations.map(async (translate) => {
                            if (currentExtensions.findIndex((e) => e.id === translate.id) === -1) {
                                return;
                            }
                            const contents = await this.registerLanguage(translate, extension.path);
                            (0, ide_core_browser_1.registerLocalizationBundle)({
                                languageId,
                                languageName: localization.languageName,
                                localizedLanguageName: localization.localizedLanguageName,
                                contents,
                            }, translate.id);
                        }));
                        if (!this.storagePath) {
                            this.storagePath = (await this.extensionStoragePathServer.getLastStoragePath()) || '';
                        }
                        promises.push(this.extensionNodeService.updateLanguagePack(currentLanguage, extension.path, this.storagePath));
                    }
                }
            }
            await Promise.all(promises);
            this._whenContributed.resolve();
        }
        catch (error) {
            this.logger.error('Failed to contribute localizations:', error);
            this._whenContributed.reject(error);
        }
    }
    async registerLanguage(translate, extensionPath) {
        const bundlePath = new Path(extensionPath).join(translate.path.replace(/^\.\//, '')).toString();
        const { content } = await this.fileServiceClient.readFile(ide_core_browser_1.URI.file(bundlePath).toString());
        const json = this.safeParseJSON(content.toString());
        const contents = {};
        if (json.contents) {
            for (const path of Object.keys(json.contents)) {
                if (json.contents[path]) {
                    for (const key of Object.keys(json.contents[path])) {
                        contents[key] = json.contents[path][key];
                    }
                }
            }
        }
        return contents;
    }
};
exports.LocalizationsContributionPoint = LocalizationsContributionPoint;
tslib_1.__decorate([
    (0, di_1.Autowired)(ide_core_browser_1.PreferenceService),
    tslib_1.__metadata("design:type", Object)
], LocalizationsContributionPoint.prototype, "preferenceService", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(ide_extension_storage_1.IExtensionStoragePathServer),
    tslib_1.__metadata("design:type", Object)
], LocalizationsContributionPoint.prototype, "extensionStoragePathServer", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(ide_core_browser_1.ILogger),
    tslib_1.__metadata("design:type", Object)
], LocalizationsContributionPoint.prototype, "logger", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(common_1.IFileServiceClient),
    tslib_1.__metadata("design:type", Object)
], LocalizationsContributionPoint.prototype, "fileServiceClient", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(common_2.ExtensionNodeServiceServerPath),
    tslib_1.__metadata("design:type", Object)
], LocalizationsContributionPoint.prototype, "extensionNodeService", void 0);
tslib_1.__decorate([
    (0, di_1.Autowired)(types_1.AbstractExtInstanceManagementService),
    tslib_1.__metadata("design:type", types_1.AbstractExtInstanceManagementService)
], LocalizationsContributionPoint.prototype, "extensionManageService", void 0);
exports.LocalizationsContributionPoint = LocalizationsContributionPoint = tslib_1.__decorate([
    (0, di_1.Injectable)(),
    (0, common_2.Contributes)('localizations'),
    (0, common_2.LifeCycle)(2 /* LifeCyclePhase.Initialize */)
], LocalizationsContributionPoint);
/**
 * zh-cn -> zh-CN
 * en-us -> en-US
 * ja -> ja
 * @param id
 */
function normalizeLanguageId(id) {
    const parts = id.split('-');
    if (parts[1]) {
        parts[1] = parts[1].toUpperCase();
    }
    return parts.join('-');
}
//# sourceMappingURL=localization.js.map