Ext.define('Portfolio.designer.ui.domainModelEntityHierarchyTree', {
	extend: 'Ext.tree.Panel',
	alias: ['widget.ip2DomainModelEntityHierarchyTree'],
	rootVisible: false,
	width: 300,
	requires: [
		"Portfolio.designer.model.domainModelEntityHierarchyTree"
	],
	config: {
		entity: {},
		designer: null
	},
	initComponent: function() {

		var i_self = this;
		var o_root = {};
		var o_entity = i_self.getEntity();

		if (o_entity.extend) {
			o_root = i_self.buildHierarchy(o_entity.extend.entity, o_entity.extend.baseTable, o_entity.extend);
		}

		i_self.store = Ext.create('Ext.data.TreeStore', {
			model: "Portfolio.designer.model.domainModelEntityHierarchyTree",
			root: o_root,
			proxy: {
				type: 'memory'
			}
		});

		i_self.callParent();
	},

	buildHierarchy: function(s_entity, s_baseTable, o_values) {

		var i_self = this;
		var i_designer = i_self.getDesigner();

		var o_source = o_values;

		var a_extentions = [];

		if (s_entity) {

			var a_entities = i_designer.model.entities;
			var s_extend = s_entity;

			while (s_extend) {

				var o_extend = Ext.apply({}, o_source);
				var b_entity = o_extend.entity ? true : false;

				if (!b_entity) {
					o_extend.entity = "";
					o_extend.baseTable = s_extend;
				}
				else {
					o_extend.entity = s_extend;
					o_extend.baseTable = "";
				}

				a_extentions.unshift(o_extend);

				var o_found = Ext.Array.findBy(a_entities, function(o_value) {
					return o_value.name == s_extend;
				});

				if (!o_found || !o_found.extend) {
					break;
				}

				o_source = o_found.extend;
			}
		}
		else {
			if (s_baseTable) {

				var o_extend = Ext.apply({}, o_source);

				delete o_extend.entity;

				a_extentions.push(o_extend);
			}
		}

		var o_root = Ext.apply({}, {
			expanded: true,
			expandable: false,
			children: []
		});

		var o_parent = o_root;

		Ext.Array.each(a_extentions, function(o_value, n_index) {

			var o_child = Ext.apply({}, {
				text: o_value.entity ? o_value.entity : o_value.baseTable,
				expanded: true,
				expandable: false,
				iconCls: "ip2-no-tree-icon",
				disabled: n_index == a_extentions.length - 1 ? false : true,
				children: [],
				extend: o_value
			});

			if (!o_parent.children) {
				o_parent.children = [];
			}
			o_parent.children.push(o_child);

			o_parent = o_child;
		});

		return o_root;
	}

  });
