Ext.define("Ext.ux.form.field.LanguageComboBox", {

	extend: "Ext.ux.form.field.EntityComboBox",

	alias: [
		"widget.languagecombo",
		"widget.languagecombobox"
	],

	config: {
		dmd: "dmd/portfolio.dmd",
		entity: "NAVLNG",
		view: "portfolio",
		extraParams: null,
		localeStore: null
	},

	initComponent: function () {

		var i_self = this;

		var o_initalConfig = i_self.initialConfig || {};

		Ext.applyIf(o_initalConfig, {
			dmd: i_self.getDmd(),
			entity: i_self.getEntity(),
			view: i_self.getView(),
			extraParams: i_self.getExtraParams()
		});

		i_self.createLocaleStore();

		i_self.callParent(arguments);

		return i_self;
	},

	createLocaleStore: function() {

		var i_self = this;

		var i_store = Ext.create("Ext.ux.data.store.Locale", {});

		i_self.setLocaleStore(i_store);
	},

	getRenderFn: function() {

		var i_self = this;
		var a_fields = i_self.getDisplayFields();

		var i_localStore = i_self.getLocaleStore();

		var f_renderer = function (v) {

			v = v || {};
			var s_value = null;
			var a_values = [];

			Ext.Array.each(a_fields, function(s_field) {
				if (v[s_field]) {
					a_values.push(ip2.i18n(v[s_field]));
				}
			});

			if (a_values.length > 0) {

				a_values = Ext.Array.map(a_values, function(value) {

					var i_record = i_localStore.findRecord("code", value);

					var s_return = value;

					if (i_record) {
						s_return = ip2.i18n(i_record.get("language"));
					}

					return s_return;
				});

				if (a_values.length == 1) {
					s_value = a_values[0];
				}
				else {
					s_value = a_values.join(" - ");
				}
			}

			return s_value;
		};

		return f_renderer;
	},

	getRenderTemplate: function(f_renderer) {

		var i_self = this;

		var i_localStore = i_self.getLocaleStore();

		f_renderer = Ext.isFunction(f_renderer) ? f_renderer : i_self.getRenderFn();

		var i_tpl = Ext.create("Ext.XTemplate",
			"<tpl for=\".\">",
				"<li role=\"option\" class=\"x-boundlist-item\" style=\"text-overflow: ellipsis; white-space: nowrap; overflow:hidden;\">",
					"<img src=\"{[this.getFlag(values.LNGID)]}\" style=\"padding-right:10px; vertical-align:middle; width:32px; height: 16px;\" />",
					"{[this.renderer(values)]}",
				"</li>",
			"</tpl>",
			{
				getFlag: function(s_id) {

					var i_record = i_localStore.findRecord("code", s_id);

					var s_result = "";

					if (i_record) {
						s_result = "/portfolio/styles/icon/flags/" + i_record.get("flag") + ".png";
					}

					return s_result;
				},
				renderer: f_renderer
			}
		);

		return i_tpl;
	},

	getTemplate: function() {

		var i_self = this;

		var i_tpl = Ext.create("Ext.XTemplate",
			"<tpl for=\".\">",
				"{[typeof values === \"string\" ? values : this.renderer(values)]}",
			"</tpl>",
			{
				renderer: i_self.getRenderFn()
			}
		);
		return i_tpl;
	}
});
