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

	extend: "Ext.panel.Panel",

	alias: [
		"widget.ip2DomainModelEntityKeyManager"
	],

	layout: {
		type: "border"
	},

	config: {
		keySelector: null,
		keyGrid: null,
		entity: null,
		entityManager: null,
		required: false
	},

	initComponent: function() {

		var i_self = this;
		i_self.callParent();

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

	requires: [
		"Portfolio.designer.ui.domainModelEntityKeySelector",
		"Portfolio.designer.ui.domainModelEntityKeyGrid"
	],

	createItems: function() {

		var i_self = this;
		var i_entityManager = i_self.getEntityManager();
		var i_columnManager = i_entityManager.columnManager;
		var o_entity = i_self.getEntity();
		var a_items = [];

		var i_keyStore = i_columnManager.columnGrid.getStore();

		var i_selector = Ext.widget("ip2DomainModelEntityKeySelector", {
			entity: o_entity,
			flex: 1,
			region: "south",
			hidden: true,
			store: i_keyStore,
			disabled: i_self.getRequired(),
			border: false,
			bodyPadding: 5,
			toFieldChange: function(list) {

				var i_grid = i_self.getKeyGrid();
				var a_records = i_grid.getSelectionModel().getSelection();
				var i_record = a_records[0];

				i_record.set("columns", list);
			}
		});

		var i_grid = Ext.widget("ip2DomainModelEntityKeyGrid", {
			entityManager: i_entityManager,
			entity: o_entity,
			selector: i_selector,
			flex: 1,
			region: "center",
			required: i_self.getRequired()
		});

		i_self.setKeySelector(i_selector);
		i_self.setKeyGrid(i_grid);

		a_items.push(i_selector);
		a_items.push(i_grid);

		return a_items;
	},

	doSave: function(o_entity) {

		var i_self = this;

		var i_grid = i_self.getKeyGrid();
		var i_store = i_grid.getStore();

		o_entity = o_entity || i_self.getEntity() || {};

		var a_keys = [];

		var a_records = i_store.getRange();

		Ext.Array.each(a_records, function(i_record) {

			var o_key = {};

			Ext.Object.each(i_record.data, function(s_key) {

				switch (s_key) {
				case "columns":
					var a_columns = i_record.get("columns") || [];
					o_key[s_key] = a_columns;
					break;
				case "primary":
					if (i_record.get(s_key)) {
						o_key[s_key] = i_record.get(s_key);
					}
					break;
				case "was":
					if (i_record.get(s_key).length > 0) {
						o_key[s_key] = i_record.get(s_key);
					}
					break;
				default:
					o_key[s_key] = i_record.get(s_key);
					break;
				}
			});

			delete o_key.drop;
			delete o_key.was;

			a_keys.push(o_key);
		});

		if (a_keys.length > 0) {
			Ext.apply(o_entity, {
				keys: a_keys
			});
		}
		else {
			delete o_entity.keys;
		}

		return a_keys;
	}
});
