/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the Source EULA. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as fs from 'fs';
import { FileAccess } from 'vs/base/common/network';
import * as path from 'vs/base/common/path';

import * as lp from 'vs/base/node/languagePacks';
import product from 'vs/platform/product/common/product';

const metaData = path.join(FileAccess.asFileUri('').fsPath, 'nls.metadata.json');
const _cache: Map<string, Promise<lp.NLSConfiguration>> = new Map();

function exists(file: string) {
	return new Promise(c => fs.exists(file, c));
}

export function getNLSConfiguration(language: string, userDataPath: string): Promise<lp.NLSConfiguration> {
	return exists(metaData).then((fileExists) => {
		if (!fileExists || !product.commit) {
			// console.log(`==> MetaData or commit unknown. Using default language.`);
			// The OS Locale on the remote side really doesn't matter, so we return the default locale
			return Promise.resolve({ locale: 'en', osLocale: 'en', availableLanguages: {} });
		}
		const key = `${language}||${userDataPath}`;
		let result = _cache.get(key);
		if (!result) {
			// The OS Locale on the remote side really doesn't matter, so we pass in the same language
			result = lp.getNLSConfiguration(product.commit, userDataPath, metaData, language, language).then(value => {
				if (InternalNLSConfiguration.is(value)) {
					value._languagePackSupport = true;
				}
				return value;
			});
			_cache.set(key, result);
		}
		return result;
	});
}

export namespace InternalNLSConfiguration {
	export function is(value: lp.NLSConfiguration): value is lp.InternalNLSConfiguration {
		const candidate: lp.InternalNLSConfiguration = value as lp.InternalNLSConfiguration;
		return candidate && typeof candidate._languagePackId === 'string';
	}
}
