Ext.define("IceCap.ux.form.field.sqlComboBox", {

	extend: "Ext.form.field.ComboBox",

	alias: [
		"widget.DDSQL"
	],

	minChars: 1,

	valueField: "KEY",

	displayField: "VALUE",

	typeAhead: true,

	mode: "remote",

	triggerAction: "all",

	selectOnFocus: true,

	matchFieldWidth: false,

	editable: true,

	config: {
		sqlVoucher: ""
	},

	listeners: {
		keydown: {
			fn: function(i_field, i_event) {

				var n_key = i_event.getKey();
				
				if (i_field.isExpanded) {
					if (n_key == Ext.event.Event.DOWN || n_key == Ext.event.Event.UP) {
						i_event.stopEvent();
					}
				}
			}
		}
	},

	initComponent: function() {

		var i_self = this;
		var i_store = i_self.createStore();

		i_self.store = i_store;
		i_self.callParent();

		var i_model = i_store.getModel();

		var value = i_self.getValue();
		var rawValue = i_self.getRawValue();

		var i_created = i_model.create({
			KEY: rawValue,
			VALUE: value
		});

		if (i_created.get(i_created.idProperty)) {
			i_store.add(i_created);
		}
	},

	initValue: function() {

		var i_self = this;

		var i_store = i_self.getStore();

		var i_model = i_store.getModel();

		var value = i_self.value || null;

		var a_loaded = [];

		if (Ext.isEmpty(value)) {
			value = null;
		}

		var a_values = Ext.Array.from(value);

		var n_load = a_values.length;

		if (n_load) {
			var a_load = [];

			var a_result = [];

			Ext.Array.each(a_values, function(value) {

				var i_test = i_model.create({});
				i_test.set(i_model.idProperty, value);

				if (i_test.get(i_model.idProperty) === value) {
					a_load.push(value);
				}
			});

			if (a_load.length > 0) {

				i_store.load({
					callback: function(a_records, i_store) {

						a_records = Ext.Array.from(a_records);

						if (a_records.length === 0) {
							value = null;
						}

						i_self.suspendCheckChange++;
						i_self.setValue(value);
						i_self.suspendCheckChange--;
					}
				});

				i_self.originalValue = i_self.lastValue = value;
				i_self.resetOriginalValue();
			}
			else {

				i_self.suspendCheckChange++;
				i_self.setValue(null);
				i_self.suspendCheckChange--;
				i_self.originalValue = i_self.lastValue = null;
				i_self.resetOriginalValue();
			}
		}
		else {
			i_self.originalValue = i_self.lastValue = i_self.getValue();
			i_self.resetOriginalValue();
		}
	},

	createStore: function() {

		var i_self = this;

		var i_store = Ext.create("Ext.data.Store", {
			fields: [
				{
					name: "KEY",
					type: "auto"
				},
				{
					name: "VALUE",
					type: "auto"
				}
			],
			pageSize: i_self.pageSize || 25,
			proxy: {
				url: "/icecap/DDSQL.aspx?runSql=runsql&sqlVoucher=" + i_self.getSqlVoucher(),
				type: "ajax",
				reader: {
					type: "json"
				}
			},
			idProperty: "VALUE"
		});

		return i_store;
	}
});
