Ext.ns('App');
Ext.ns('App.util');

App.util.Translation = function() {

	var oTranslationStore = null;

	var cfg = {
		languageId: 0,
		url: '',

		data: null,

		callback: Ext.emptyFn,
		scope: this	// window
	};

	return {

		init: function(config) {

			Ext.apply(cfg, config);

			var storeConfig = {
				idProperty: 'translation_label',

				fields: [
					{name: 'translation_label', type: 'string'},
					{name: 'translation_string', type: 'string'}
				],

				baseParams: {
					lang_id: cfg.languageId
				},

				listeners: {
					load: {
						fn: function(store) {
							cfg.callback.apply(cfg.scope, [this]);
						},
						scope: this
					}
				}
			}

			if (cfg.url) {
				storeConfig.autoLoad = true;
				storeConfig.root = 'data';
				storeConfig.url = cfg.url;
			} else if (cfg.data) {
				storeConfig.data = cfg.data;
			}

			oTranslationStore = new Ext.data.JsonStore(storeConfig);

		},

		/**
		 * Returns the translated string for the specified label.
		 * 
		 * @param {String} label
		 * @param {String} replaceLfText Optional. If set, this text replaces
		 *     all line feeds in the returned string. Defaults to <br />
		 * @return {String} The translated string.
		 */
		get: function(label, replaceLfText) {
			var record;
			if (oTranslationStore && (record = oTranslationStore.getById(label))) {
				return record.get('translation_string').replace(/\\n/g, replaceLfText || '<br />');
			}
			return String.format('Untranslated label: {0}', label);
		}

	}
}();
