
Ext.define('Ext.ux.form.field.snaponicon.Text', {

	requires: [
		'Ext.form.field.Text',
		'Ext.ux.data.store.SnapOnIcon'
	], 

	extend: 'Ext.form.field.Text',

	alias: [
		'widget.snaponicontextfield'
	],

	enableKeyEvents: true,

	minChars: 0,

	queryParam: 'keyword',

	_PADDINGLEFT: 0,

	listeners: {
		'afterrender': {
			fn: function(self) {

				var value = this.getValue();

				if (value)
					self.setInputIcon(value);
			},
			single: true
		},
		'change': {
			fn: function(self, newValue, oldValue) {

				var minChars = self.minChars;

				if (newValue.length && newValue.length > minChars) {
					self.setInputIcon(newValue);
				}
				else {
					self.clearInputIcon();
				}
			}
		}
	},

	initComponent: function() {

		var text = this;

		text.store = Ext.create('Ext.ux.ip2.data.store.SnapOnIcon');

		text.callParent();

		return text;
	},

	clearInputIcon: function() {

		var text = this,
			inputEl = text.inputEl;

		// TODO: Check for error state to not be intrusive!

		if (inputEl && inputEl.dom) {

			inputEl.setStyle({
				'padding-left': text._PADDINGLEFT,
				'background-image': 'none'
			});
		}
	},

	// private
	getParams: function(queryString) {
		
		var params = {},
			param = this.queryParam;

		if (param) {
			params[param] = queryString;
		}
		
		return params;
	},

	loadSnapOnIcons: function(keyword, fnCallback) {

		var text = this;

		if (keyword && keyword.length) {
			
			text.store.load({
				params: text.getParams(keyword),
				callback: function(records, operation, success) {
					if (Ext.isFunction(fnCallback))
						fnCallback.call(text, records, operation, success)
				}
			});
		}

		return text;
	},

	setInputIcon: function(keyword) {

		var text = this,
			inputEl = text.inputEl;

		if (inputEl && inputEl.dom) {

			if (!text._PADDINGLEFT)
				text._PADDINGLEFT = inputEl.getStyle('paddingLeft');

			text.loadSnapOnIcons(keyword, function(records) {

				var record = records[0],
					icon;

				if (records) {

					 icon = records[0].data.icon;

					inputEl.setStyle({
						'padding-left': parseInt(text._PADDINGLEFT) + 20 + 'px',
						'background-image': 'url(' + icon + ')',
						'background-repeat': 'no-repeat',
						'background-position': text._PADDINGLEFT + ' center'
					});
				}
			});
		}

		return this;
	}
})
