Ext.define('Ext.ux.folderorganizer.FamilyOrganizer', {
	extend: 'Ext.ux.folderorganizer.Organizer',
	initComponent: function() {
		var me = this;

		me.models = {};
		me.counter = 0;

		var dmdName = me.dmd;
		var dmdPath = me.dmd;
		var xpdName = me.xpd;
		var xpdPath = me.xpd;

		// family
		// ------
		Ext.define('family', {
			extend: 'Ext.data.Model',
			fields: [
			{ name: 'ID', type: 'string' },
			{ name: 'KEY', type: 'string' },
			{ name: 'GROUP', type: 'string', title: 'Group', flex: 1, groupColumn: true },
			{ name: 'leaf', type: 'boolean' },
			{ name: 'allowDrag', type: 'boolean' },
			{ name: 'allowDrop', type: 'boolean' },
			{ name: 'allowEdit', type: 'boolean' },
			{ name: 'allowRemove', type: 'boolean' },
			{ name: 'iconCls', type: 'string' }
			],
			idProperty: 'ID',
			proxy: {
				type: 'ajax',
				url: me.serviceUrl,
				extraParams: {
					action: 'familyTreeStore',
					displayRootNode: true,
					dmd: dmdPath,
					xpd: xpdPath,
					entity: 'WSHITMET00',
					uiName: 'portfolio',
					titleColumns: Ext.encode(me.titleColumns)
				}
			}
		});
		me.belongTo.model = 'family';
		me.belongTo.propertyNameMapping = {
			ID: 'IFMIFMTKN',
			PARENTID: 'IFMPNTTKN',
			NAME: 'IFMNAM',
			SHARED: 'IFMSHRPROP'
		};

		// writer model (used to add/update)
		// ---------------------------------
		me.models.writer = ip2.model({
			dmd: dmdName,
			entityName: 'WSHIFMET00'
		});
		me.belongTo.writerModel = me.models.writer.modelName;
		me.belongTo.cid = (me.cid) ? me.cid : [];

		// vare propertites
		// ----------------
		me.models.item = ip2.model({
			dmd: dmdName,
			entityName: 'WSHITMET00'
		});
		Ext.apply(me.models.item.proxy.extraParams, {
			dmdFile: dmdPath,
			uiName: 'portfolio',
			context: 'grid',
			action: 'getRows'
		});
		me.hasMany.model = me.models.item.modelName;
		if (Ext.isArray(me.hasMany.items)) {
			for (var i = 0; i < me.hasMany.items.length; i++) {
				me.hasMany.items[i].model = me.models.item.modelName;
				me.hasMany.items[i].displayColumns = me.titleColumns;
				me.hasMany.items[i].displayFilterField = true;
				me.hasMany.items[i].buttons = ['refresh'];
			}
		}

		me.belongTo.doCreate = function(parentNode, selection, setChecked, dropped) {
			// call per dropped item
			var me = this;

			var childNode;
			var params = {};

			var action = 'add';
			var dragFrom = 'family2family';

			if (selection.store && selection.store.name) {
				dragFrom = selection.store.name;
			}
			else if (selection.childNodes) {
				if (selection.data.ID.substring(0, 4) == 'item') {
					action = 'update';
					dragFrom = 'familyProductGrid';
				} if (selection.data.ID.substring(0, 4) == 'prel') {
					action = 'update';
					dragFrom = 'relatedProductGrid';
				}
			}

			// if dragged record from grid (not tree grid), create new childnode
			if (!selection.childNodes && parentNode.isLoaded()) {
				childNode = me.createNewNode(selection, parentNode, dragFrom);
				if (parentNode && parentNode.isLoaded()) {
					parentNode.insertChild(0, childNode);
				}
			}

			// dragged from family to family
			if (dragFrom == 'family2family') {
				params = {
					action: 'updateFamily',
					ID: selection.data.KEY,
					PARENTID: parentNode.data.KEY
				};
				Ext.Ajax.request({
					url: me.wrapper.serviceUrl,
					params: params,
					node: selection,
					success: function(response, request) {
          }
				});

				// drag from product in family
			}
			else if (dragFrom == 'familyProductGrid') {
				// if existing record, move to new parent ?
				if (action == 'update') {
					params = {
						action: 'updateFamilyProduct',
						item: selection.data.KEY,
						family: parentNode.data.KEY
					};
				}
				else {
					params = {
						action: 'updateFamilyProduct',
						item: selection.data[selection.store.model.prototype.idProperty],
						family: parentNode.data.KEY
					};
				}
				Ext.Ajax.request({
					url: me.wrapper.serviceUrl,
					params: params,
					parentNode: parentNode,
					childNode: childNode,
					selection: selection,
					success: function(response, request) {
						var result = {};
						eval('result =' + response.responseText);
						if (result.success) {
							request.selection.store.remove(request.selection);
						}
					}
				});

				// add related product
			}
			else if (dragFrom == 'relatedProductGrid') {

				if (action == 'update') {
					selection.set('FAMILY', parentNode.data.KEY);
					params = {
						action: 'updateRelatedProduct',
						id: selection.data.KEY,
						family: parentNode.data.KEY
					};
				}
				else {
					params = {
						action: 'addRelatedProduct',
						item: selection.data.ITMITMTKN,
						family: parentNode.data.KEY
					};
				}
				Ext.Ajax.request({
					url: me.wrapper.serviceUrl,
					params: params,
					parentNode: parentNode,
					childNode: childNode,
					selection: selection,
					success: function(response, request) {
						var result = {};
						eval('result =' + response.responseText);
						if (result.success && result.newID) {
							if (request.childNode) {
								request.childNode.set('ID', 'prel.' + result.newID);
								request.childNode.set('KEY', result.newID);
							}
						}
					}
				});
			}
		};

		me.belongTo.doDelete = function(node) {
			// family
			if (node.data.ID.substring(0, 4) == 'fami') {
				// remove family
				Ext.Ajax.request({
					url: me.wrapper.serviceUrl,
					params: {
						action: 'removeFamily',
						family: node.data.KEY
					}
				});

				// reload grid store
				var grid = me.hasMany.familyProductGrid;
				if (grid) {
					grid.getStore().load();
				}
				// product in family
			}
			else if (node.data.ID.substring(0, 4) == 'item') {
				// remove family
				Ext.Ajax.request({
					url: me.wrapper.serviceUrl,
					params: {
						action: 'removeFamilyProduct',
						item: node.data.KEY
					}
				});

				// add node to product grid
				var grid = me.hasMany.familyProductGrid;
				if (grid) {
					var store = grid.getStore();

					// get data for single record that has been remove
					var filter = [{
						property: 'ITMITMTKN',
						value: node.data.KEY
					}];
					var params = {
						model: 'WSHITMET00',
						dmdFile: me.models.item.proxy.extraParams.dmdFile,
						uiName: me.models.item.proxy.extraParams.uiName,
						context: me.models.item.proxy.extraParams.context,
						action: me.models.item.proxy.extraParams.action,
						filter: Ext.encode(filter),
						language: me.models.item.proxy.extraParams.language,
						languageColumn: me.models.item.proxy.extraParams.languageColumn
					};
					Ext.Ajax.request({
						url: '/ip2-services/ip2dmdProxy.aspx',
						params: params,
						method: 'GET',
						success: function(response, request) {
							var result = {};
							eval('result =' + response.responseText);
							if (result.totalRows > 0) {
								var record = new store.model(result.rows[0]);
								store.insert(0, record);
							}
						}
					});
				}

				// else, product in relation
			}
			else if (node.data.ID.substring(0, 4) == 'prel') {
				// remove related product
				Ext.Ajax.request({
					url: me.wrapper.serviceUrl,
					params: {
						action: 'removeRelatedProduct',
						id: node.data.KEY
					}
				});
			}

			// remove node from product grid
			node.remove();
		};

		me.belongTo.addRow = function() {
			var me = this;

			var model = me.writerStore.proxy.getModel();
			var record = new model;

			var nodes = me.treegrid.getSelectionModel().getSelection();
			node = nodes[0];

			me.dmdEditor(me.writerStore, record, node, 'new');
		};

		me.belongTo.createNewNode = function(record, node, dragFrom) {
			var me = this;

			var data = me.buildNodeData(record, dragFrom);

			if (node && node.data.ID) {
				data.PARENTID = node.data.KEY;
				record.set('IFMPNTTKN', data.PARENTID);
				if (data.PARENTID == 0) {
					record.set('IFMSHRPROP', '{"format":{},"color":{"dep":"format"}}');
				}
				record.save({
					getRecords: function() {
						return [record];
					}
				});
			}

			return Ext.create(me.store.model.modelName, data);
		};

		me.belongTo.buildNodeData = function(record, dragFrom) {
			var me = this;

			var data = {
				leaf: false,
				allowDrag: true,
				allowDrop: true,
				allowEdit: true,
				allowRemove: true
			};

			if (dragFrom) {
				var title = '';
				data.KEY = record.data.ITMITMTKN || record.data.KEY;

				if (dragFrom == 'familyProductGrid') {
					data.ID = 'item.' + record.data.ITMITMTKN;
					data.iconCls = 'dpd-icon-family';
					data.leaf = true;
				}
				else if (dragFrom == 'relatedProductGrid') {
					data.ID = 'prel.' + record.data.ITMITMTKN;
					data.iconCls = 'dpd-icon-related';
					data.leaf = true;
				}

				var columns = me.titleColumns;
				if (columns) {
					for (var i = 0; i < columns.length; i++) {
						if (record.data[columns[i]]) {
							title = me.concatTitle(title, record.data[columns[i]]);
						}
					}
				}
				data.GROUP = title;
			}
			else {
				data.KEY = record.data.IFMIFMTKN || record.data.KEY;
				data.ID = 'fami.' + record.data.IFMIFMTKN;
				data.GROUP = record.data.IFMNAM || record.data.GROUP;
			}

			return data;
		};
		me.belongTo.updateRow = function(node) {
			var me = this;

			if (!node) {
				var nodes = me.treegrid.getSelectionModel().getSelection();
				node = nodes[0];
			}

			if (!node) {
				return;
			}

			if (node.data.allowEdit) {
				me.getRecord({
					node: node,
					success: function(args) {
						me.dmdEditor(me.writerStore, args.record, args.node, 'update');
					}
				});
			}
		};

		me.belongTo.isAddAllow = function(node) {
			if (node.data.ID.substring(0, 4) == 'item' || node.data.ID.substring(0, 4) == 'prel') {
				return false;
			}
			else {
				return true;
			}
		};

		me.belongTo.getKey = function(node) {
			key = {};
			if (node) {
				key.IFMIFMTKN = node.data.KEY;
			}
			return key;
		};

		me.belongTo.nodeDropPoint = function(dragNode, targetNode, position) {
			if (position == 'append') {
				return true;
			}
			else {
				return false;
			}
		};

		me.belongTo.isTreeNodeDrag = function(node) {
			if (this.isNode(node)) {
				if (node.data.ID.substring(0, 4) == 'fami' || node.data.ID.substring(0, 4) == 'item' || node.data.ID.substring(0, 4) == 'prel') {
					return true;
				}
				else {
					return false;
				}
			}
			else {
				return false;
			}
		};

		me.belongTo.hasSequenceProperty = function(node) {
			return false;
		};

		me.callParent();
	}
});
