Ext.define('Ext.ux.form.field.BasketItems', {

	requires: [
		'Ext.container.Container',
		'Ext.form.field.Field'
	],

	extend: 'Ext.container.Container',

	alias: [
		'widget.ip2basketitems',
		'widget.ip2BasketItems'
	],

	mixins: {
		field: 'Ext.form.field.Field'
	},

	changeListener: function() {
		var i_cmp = this;

		var s_value = this.getValue();

		var o_value;

		try {
			o_value = JSON.parse(s_value);
		}
		catch (e) {
			o_value = s_value;
		}

		var a_itemTokens = Ext.Array.map(o_value.rows, function(o_item) {
			return [o_item.itemToken, o_item.quantity || 1].join(':');
		});

		var o_xpd = ip2.resource.get('product.xpd', true);

		// Back in the good ol days we called the product.xpd for itemprop.xpd
		if (!o_xpd) {
			o_xpd = ip2.resource.get('itemprop.xpd', true);
		}

		var o_props = o_xpd.collections.all;

		var a_fields = [];
		var a_columns = [];

		Ext.Object.each(o_props, function(key, o_prop) {
			if (o_prop.grids && Ext.Array.indexOf(o_prop.grids, 'basket') > -1) {
				a_fields.push(key);

				a_columns.push({
					header: ip2.xpd.translate(o_xpd, o_prop.title),
					dataIndex: key
				});
			}
		});

		// {"rows":[{"itemToken":"347","quantity":3,"tkn":0.11544480361044407},{"itemToken":"35","quantity":12,"tkn":0.016003133729100227},{"itemToken":"337","quantity":3,"tkn":0.6085524319205433},{"itemToken":"22","quantity":3,"tkn":0.20539662498049438,"uom":"STK"}]}
		Ext.Ajax.request({
			url: '/pp-services/getitm.aspx',
			params: {
				action: 'getitms',
				items: a_itemTokens.join(',')
			},
			success: function(response) {
				var o_resp = JSON.parse(response.responseText);

				a_rows = Ext.Array.map(o_value.rows, function(o_item, key) {
					var o_data;

					Ext.Array.some(o_resp.rows, function(o) {
						if (o.itemToken == o_item.itemToken || o.id == o_item.itemToken || o.itmitmtkn == o_item.itemToken) {
							o_data = o;
							return true;
						}
					});

					return o_data ? Ext.apply(o_item, o_data) : o_item;
				});

				Ext.Array.each(a_rows, function(o_item) {
					o_item.id = o_item.tkn;
				});

				i_cmp.removeAll();
				i_cmp.add({
					xtype: 'grid',
					store: {
						fields: a_fields,
						data: {
							rows: a_rows
						},
						proxy: {
							type: 'memory',
							reader: {
								type: 'json',
								root: 'rows'
							}
						}
					},
					columns: a_columns
				});
			}
		});
	},

	initComponent: function() {

		this.on('change', this.changeListener);

		this.callParent(arguments);

		return this;
	},
	disable: function () {
		return this;
	},
	enable: function () {
		return this;
	}
});
