/**
 * @class Ext.ux.itemreference.EntityProperties
 *
 * @extend Ext.form.field.ComboBox
 *
 * ComboBox for dmd entity properties.
 *
 * <p>Usage:</p>
 * <pre><code>
    {
        xtype: 'ip2entityPropertiesCombo',
        dmd: 'webshop.dmd',
        entity: 'names',
        serviceUrl: '/admin/services/ip2dmdproxy.aspx'
        listProperties: [
            {property: 'name'}
        ],
        cid: [1, 4, 7]
    }
 * </code></pre>
 *
 */

Ext.define('Ext.ux.itemreference.EntityProperties', {
	extend: 'Ext.form.field.ComboBox',
	alias: ['widget.ip2entityPropertiesCombo', 'widget.ip2EntityPropertiesCombo', 'widget.ip2entitypropertiescombo'],
	displayField: 'ID',
	valueField: 'ID',
	queryMode: 'remote',
	queryParam: 'search',
	triggerAction: 'all',
	minChars: 2,
	initComponent: function() {
		var me = this;

		me.setDefaults();

		me.createStore();

		var list = me.listProperties || [];
		var len = list.length;

		// create template for display field valu
		var comma = '';
		var tpl = '<tpl for=".">';
		for (var i = 0; i < len; i++) {
			tpl += comma + '{[(values.' + list[i].property + ')]}';
			comma = ', ';
		}
		tpl += '</tpl>';
		me.displayTpl = Ext.create('Ext.XTemplate', tpl);

		// create template for boundlist values
		var width;
		var defaultWidth = me.width / len;
		tpl = '<table border="0"><tpl for="."><tr class="x-boundlist-item">';
		for (var i = 0; i < len; i++) {
			width = (list[i].width) ? list[i].width : defaultWidth;
			tpl += '<td class="ip2-boundlist-cell" width="' + width + '">{' + list[i].property + '}</td>';
		}
		tpl += '</tr></tpl></table>';

		me.listConfig = {
			tpl: tpl,
			itemSelector: '.x-boundlist-item'
		};

		me.callParent();
	},

	/**
	     * @method createStore
	     *
	     * Create model and store dynamic depending on config options (dmd, entity, etc.)
	     *
	     */
	createStore: function() {
		var me = this;

		if (me.data) {
			if (Ext.isArray(me.listProperties) && me.listProperties[0].property) {
				me.displayField = me.listProperties[0].property;
			}
			me.queryMode = 'local';
			me.minChars = 1;

			me.createLocalStore();
		}
		else {
			me.createRemoteStore();
		}
	},

	/**
	     * @method createLocalStore
	     *
	     * Create store with local data (config option: 'data')
	     *
	     */
	createLocalStore: function() {
		var me = this;
		var model = "";
		var modelId = 'ip2entityPropertiesCombo_' + me.entity + '_local';

		if (Ext.ClassManager.isCreated(modelId)) {
			model = Ext.ClassManager.get(modelId);
		}

		if (!model) {
			var fields = [
			{ name: 'ID' },
			{ name: 'PARENTID' },
			{ name: 'PROPERTIES' }
			];

			// Add list properties (config option) to field definition
			for (var i = 0; i < me.listProperties.length; i++) {
				fields.push({
					name: me.listProperties[i].property
				});
			}

			Ext.define(modelId, {
				extend: 'Ext.data.Model',
				fields: fields
			});
		}

		me.store = Ext.create('Ext.data.ArrayStore', {
			autoLoad: true,
			model: modelId,
			data: me.data
		});
	},

	/**
	     * @method createRemoteStore
	     *
	     * Create store with server-side data
	     *
	     */
	createRemoteStore: function() {
		var me = this;
		var model = "";
		var modelId = 'ip2entityPropertiesCombo_' + me.entity;

		if (Ext.ClassManager.isCreated(modelId)) {
			model = Ext.ClassManager.get(modelId);
		}

		var nameConvert = function(v) {
			var props = Ext.decode(v);
			return props.name;
		};

		if (!model) {
			var fields = [
			{ name: 'ID', mapping: me.propertyNameMapping.ID },
			{ name: 'PARENTID', mapping: me.propertyNameMapping.PARENTID },
			{ name: 'PROPERTIES', mapping: me.propertyNameMapping.PROPERTIES }
			];

			// Add list properties (config option) to field definition and create convert function to parse properties
			for (var i = 0; i < me.listProperties.length; i++) {
				fields.push({
					name: me.listProperties[i].property,
					mapping: me.propertyNameMapping.PROPERTIES,
					convert: function(value) {

						var i_self = this;
						var s_key = i_self.name;
						var o_props;
						var s_value = value;

						if (value) {
							o_props = Ext.decode(value);
							s_value = o_props[s_key];
						}

						return s_value;
					}
				});
			}

			Ext.define(modelId, {
				extend: 'Ext.data.Model',
				fields: fields
			});
		}

		if (!me.dmd) {
			me.dmd = "webshop.dmd";
		}
		if (!me.serviceUrl) {
			me.serviceUrl = "/ip2-services/ip2dmdproxy.aspx";
		}

		var extraParams = {
			action: 'getRows',
			dmdFile: ip2.resource.getFullPath(me.dmd),
			entity: me.entity,
			context: 'grid',
			uiName: 'portfolio'
		};

		if (me.cid && me.cid.length > 0) {
			extraParams.filter = 'jsonPropsIn(' + me.propertyNameMapping.PROPERTIES + ', \'__cid__\', \'' + me.cid + '\') = 1';
		}

		me.store = Ext.create('Ext.data.Store', {
			model: modelId,
			autoLoad: true,
			proxy: {
				type: 'ajax',
				url: me.serviceUrl,
				extraParams: extraParams,
				reader: {
					type: 'json',
					rootProperty: 'rows',
					totalProperty: 'totalRows'
				}
			}
		});
	},

	/**
	     * @method setDefaults
	     *
	     * Set defaults config options
	     *
	     */
	setDefaults: function() {
		var me = this;

		// set property nmae mapping, if not given. Ex. used by the data model
		if (!me.propertyNameMapping) {
			if (me.entity && me.entity == 'WSHNAMET00') {
				me.propertyNameMapping = {
					ID: 'NAMNAMTKN',
					PARENTID: 'NAMPNTTKN',
					PROPERTIES: 'NAMPROP'
				};
			}
			else {
				me.propertyNameMapping = {
					ID: 'FLDFLDTKN',
					PARENTID: 'FLDPNTTKN',
					PROPERTIES: 'FLDPROP'
				};
			}
		}
		me.propertyNameMappingReverse = {};
		for (var key in me.propertyNameMapping) {
			me.propertyNameMappingReverse[me.propertyNameMapping[key]] = key.toString();
		}
	}
});
