Ext.define("Portfolio.designer.ui.domainModelEntityKeySelector", {

	extend: "Ext.panel.Panel",

	alias: [
		"widget.ip2DomainModelEntityKeySelector"
	],

	requires: [
		"Ext.ux.form.ItemSelector"
	],

	layout: {
		type: "fit"
	},

	bodyPadding: 5,

	config: {
		selector: null,
		entity: {},
		store: null,
		selectorHeight: 200
	},

	initComponent: function() {

		var i_self = this;
		i_self.callParent();

		if (!i_self.store) {
			i_self.setStore(i_self.createStore());
		}

		i_self.add(i_self.createItems());
	},

	createStore: function() {

		var i_self = this;

		var o_entity = i_self.getEntity();
		var a_data = [];

		if (Ext.isObject(o_entity.columns)) {

			Ext.Object.each(o_entity.columns, function(s_key, o_value) {
				a_data.push({
					name: o_value.name,
					title: ip2.i18n(o_value.title)
				});
			});
		}

		var i_store = Ext.create("Ext.data.Store", {
			model: "Portfolio.designer.model.domainModelEntityColumnDataModel",
			data: a_data,
			autoLoad: false
		});

		return i_store;
	},

	createItems: function() {

		var i_self = this;

		var a_items = [];

		var i_selector = Ext.create("Ext.ux.form.ItemSelector", {
			fromTitle: ip2.i18n("tableFields"),
			toTitle: ip2.i18n("keyFields"),
			height: i_self.getSelectorHeight(),
			store: i_self.getStore(),
			displayField: "name",
			valueField: "name",
			allowBlank: false,
			msgTarget: "side",
			tpl: i_self.createTemplate(),
			listeners: {
				change: {
					fn: function(i_field, value) {
						if (Ext.isArray(value)) {
							i_self.toFieldChange(value);
						}
					}
				}
			},
			multiselects: [
				{
					getInnerTpl: function() {
						return "{name} ({title})";
					}
				},
				{
					getInnerTpl: function() {
						return "{name} ({title})";
					}
				}
			]
		});

		i_self.setSelector(i_selector);

		a_items.push(i_selector);

		return a_items;
	},

	createTemplate: function() {

		var i_template = new Ext.XTemplate(
			"<tpl for=\".\">",
				"<li role=\"option\" class=\"x-boundlist-item\" style=\"text-overflow: ellipsis; white-space: nowrap; overflow:hidden;\">",
					"{[this.renderer(values.name)]}",
				"</li>",
			"</tpl>",
			{
				renderer: function(value) {

					return ip2.i18n(value);
				}
			}
		);
		return i_template;
	},

	toFieldChange: function(list) {
	},
	setToField: function(a_columns) {

		var i_self = this;
		var i_selector = i_self.getSelector();
		var a_values = [];

		if (a_columns) {
			Ext.Array.each(a_columns, function(s_name) {
				a_values.push(s_name);
			});
		}

		i_selector.setValue(a_values);
	}

  });
