Ext.define('itemReference', {
	extend: 'Ext.data.Model',
	fields: [
	{ name: 'IRFIRFTKN' },
	{ name: 'IRFGRPTKN' },
	{ name: 'IRFNAMTKN' },
	{ name: 'IRFITMNO' },
	{ name: 'NAME' },
	{ name: 'WEBSHOPNO' },
	{ name: 'PHANTON' }
	]
});

Ext.define('Ext.ux.itemreference.Grid', {
	extend: 'Ext.grid.Panel',
	alias: ['widget.ip2ItemReferenceGrid', 'widget.ip2itemReferenceGrid', 'widget.ip2itemreferencegrid'],
	border: 0,
	forceFit: true,
	layout: {
		type: 'fit'
	},
	autoScroll: true,
	width: '100%',
	initComponent: function() {
		var me = this;

		me.deletedReferences = [];
		me.previous_manufacturer = {
			IRFNAMTKN: 0,
			IRFITMNO: '',
			webshopNo: ''
		};
		me.manufacturer = {};
		me.groupToken;

		var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
			clicksToEdit: 1,
			listeners: {
				beforeedit: function(e, editor) {
					var record = me.store.getAt(e.rowIdx);
					if (record) {
						return (me.isSelf(record)) ? false : true;
					}
					return true;
				},
				edit: function(e, editor) {
					if (editor.value != editor.originalValue) {
						me.wrapper.setDirty(true);
					}
				}
			}
		});
		me.columns = [
			{ text: ip2.i18n(me.labels.manufacturerName), flex: 1, dataIndex: 'NAME' },
			{ text: ip2.i18n(me.labels.webshopNumber), flex: 1, dataIndex: 'WEBSHOPNO' },
			{ text: ip2.i18n(me.labels.manufacturerItemNumber), flex: 2, dataIndex: 'IRFITMNO', editor: { allowBlank: false }},
			{
				xtype: 'actioncolumn',
				width: 50,
				align: 'center',
				items: [{
					iconCls: "pf-delete",
					handler: function(grid, rowIndex, colIndex) {
						var record = grid.getStore().getAt(rowIndex);
						me.doDelete(record);
					}
				}],
				renderer: function (value, meta, record, row, column, store, view) {
					if (me.isSelf(record)) {
						meta.style = "display:none;";
					}
				}
			}
        ];
		me.plugins = [cellEditing];

		me.store = Ext.create('Ext.data.Store', {
			model: 'itemReference',
			proxy: {
				type: 'ajax',
				url: me.proxy + '?action=getItemReferenceRows',
				reader: {
					type: 'json',
					rootProperty: 'rows',
					totalProperty: 'totalRows'
				}
			},
			listeners: {
				load: function(store, records, successful) {
					if (successful) {
						me.groupToken = records[0].data.IRFGRPTKN;
					}
				}
			}
		});

		me.on({
			add: {
				fn: function(store, a_records) {
					me.fireEvent("dirtychange", me, me.isDirty());
				}
			},
			remove: {
				fn: function(store, a_record) {
					me.fireEvent("dirtychange", me, me.isDirty());
				}
			}
		});

		me.listeners = {
			afterrender: function() {
				if (me.manufacturer != me.previous_manufacturer) {
					me.manufacturerChanged();
				}
			}
		};

		me.callParent();

		// Catch relay change event from other tabs
		if (me.wrapper && me.wrapper.trackerParent) {

			// Set initial manufacturer object value
			var i_parent = me.wrapper.trackerParent;
			var o_values = i_parent.getValues();

			me.manufacturer.IRFNAMTKN = o_values.manufacturer;
			me.manufacturer.IRFITMNO = o_values.manufactureritemnumber;
			me.manufacturer.webshopNo = o_values.itemnumber;

			// Maintain manufacturer object value
			me.wrapper.trackerParent.on('relaychange', function(container, field, newValue) {
				if (field.name == 'manufacturer' && newValue != me.previous_manufacturer.IRFNAMTKN) {
					me.manufacturer.IRFNAMTKN = newValue;
					if (me.rendered) {
						me.manufacturerChanged();
					}
				}
				else if (field.name == 'manufactureritemnumber' && newValue != me.previous_manufacturer.IRFITMNO) {
					me.manufacturer.IRFITMNO = newValue;
					if (me.rendered) {
						me.manufacturerChanged();
					}
				}
				else if (field.name == 'itemnumber' && newValue != me.previous_manufacturer.webshopNo) {
					me.manufacturer.webshopNo = newValue;
				}
			});
		}

		me.enableBubble("dirtychange");
	},

	/* ----------------------------------------------------------------------------------------------------
	    Load new manufactorer
	   ---------------------------------------------------------------------------------------------------- */
	manufacturerChanged: function(record) {
		var me = this;

		me.store.proxy.extraParams = {
			IRFNAMTKN: me.manufacturer.IRFNAMTKN,
			IRFITMNO: me.manufacturer.IRFITMNO,
			webshopNo: me.manufacturer.webshopNo
		};
		me.store.load();
	},

	/* ----------------------------------------------------------------------------------------------------
	    Delete a row
	   ---------------------------------------------------------------------------------------------------- */
	doDelete: function(record) {
		var me = this;

		var deleteReference = function(record) {
			me.deletedReferences.push({
				IRFIRFTKN: record.data.IRFIRFTKN
			});
			me.getStore().remove(record);
		};

		if (record) {
			deleteReference(record);
		}
		else {
			var result = me.getRowSelection();
			if (result.success) {
				for (var i = 0; i < result.records.length; i++) {
					deleteReference(result.records[0]);
				}
			}
		}
	},

	/* ----------------------------------------------------------------------------------------------------
	    Get selection
	   ---------------------------------------------------------------------------------------------------- */
	getRowSelection: function() {
		var me = this;

		var result = {};

		result.records = me.getSelectionModel().getSelection();
		if (result.records.length == 0) {
			Ext.MessageBox.show({
				msg: 'Du skal vælge en række først.'
			});

			setTimeout(function() {
				Ext.MessageBox.hide();
			}, 1000);

			result.success = false;
		}
		else {
			result.success = true;
		}
		return result;
	},

	/* ----------------------------------------------------------------------------------------------------
	    Check if the row is it self
	   ---------------------------------------------------------------------------------------------------- */
	isSelf: function(record) {
		return (record.data.PHANTON || (record.data.IRFNAMTKN == this.manufacturer.IRFNAMTKN && record.data.IRFITMNO == this.manufacturer.IRFITMNO)) ? true : false;
	},

	isDirty: function() {

		var i_self = this;
		var i_store = i_self.getStore();
		var b_dirty = false;
		var a_records = i_store.getData().items;
		ip2.each(a_records, function(i_record) {
			if (i_record.dirty) {
				b_dirty = i_record.dirty;
			}
		});
		return b_dirty;
	},

	/* ----------------------------------------------------------------------------------------------------
	    Do Save
	   ---------------------------------------------------------------------------------------------------- */
	doSave: function() {
		var me = this;

		var rows = [];

		var totalRows = me.store.getCount();
		for (var i = 0; i < totalRows; i++) {
			var record = me.store.getAt(i);
			if (record.dirty) {
				var data = {};
				data.rowIndex = i;
				data.IRFIRFTKN = record.data.IRFIRFTKN;
				data.IRFGRPTKN = record.data.IRFGRPTKN;
				data.IRFNAMTKN = record.data.IRFNAMTKN;
				data.IRFITMNO = record.data.IRFITMNO;
				data.action = (data.IRFIRFTKN == 0) ? 'add' : 'update';
				rows.push(data);
				if (me.groupToken == 0 && data.IRFGRPTKN > 0) {
					me.groupToken = data.IRFGRPTKN;
				}
				record.commit();
			}
		}

		// If only one record let and it is itself, then deleted
		if (totalRows == 1) {
			var record = me.store.getAt(0);
			if (me.isSelf(record)) {
				if (record.data.IRFIRFTKN > 0) {
					me.deletedReferences.push({
						IRFIRFTKN: record.data.IRFIRFTKN
					});
					record.set('IRFIRFTKN', 0);
				}
				rows = [];

				// prepar for new group
				me.groupToken = 0;
			}
		}

		// Add deleted rows to array
		for (var i = 0; i < me.deletedReferences.length; i++) {
			var data = {};
			data.IRFIRFTKN = me.deletedReferences[i].IRFIRFTKN;
			data.action = 'delete';
			rows.push(data);
		}
		me.deletedReferences = [];

		if (rows.length > 0) {
			Ext.Ajax.request({
				url: me.proxy,
				params: {
					action: 'updateItemReferenceRows',
					groupToken: me.groupToken,
					rows: Ext.encode(rows)
				},
				success: function(response, request) {
					var result = {};
					eval('var result = ' + response.responseText);
					if (result.success) {
						if (result.groupToken) {
							me.groupToken = result.groupToken;
						}
						if (result.tokens) {
							var rows = Ext.decode(request.params.rows);
							var tokens = result.tokens.split(',');
							for (var i = 0; i < tokens.length; i++) {
								var index = rows[i].rowIndex;
								var record = me.store.getAt(index);
								record.set('IRFIRFTKN', parseInt(tokens[i]));
								record.commit();
							}
						}
					}
				}
			});
		}

		me.fireEvent('savecomplete', me, true);
	}

});
