Ext.define("Ext.ux.buffer.view.Form", {
	extend: "Ext.form.Panel",

	requires: [
		"Ext.ux.buffer.Proxy",
		"Ext.ux.buffer.Store",
		"Ext.ux.buffer.controller.Form"
	],

	alias: [
		"widget.ux.buffer.view.form",
		"widget.legacy.storeform"
	],

	config: {
		store: null,
		url: null,
		idProperty: null
	},

	trackResetOnLoad: true,

	controller: "ux.buffer.controller.form",

	initComponent: function() {

		var i_self = this;

		i_self.callParent(arguments);

		i_self.createStore();
		i_self.addHandler();
	},

	createStore: function() {

		var i_self = this;
		var i_form = i_self.getForm();
		var a_result = i_form.getFields();

		var a_fields = [];

		Ext.Array.each(a_result.items, function(i_field) {
			var o_config = Ext.apply({
				name: i_field.name
			});

			o_config.type = "auto";
			a_fields.push(o_config);
		});

		var s_url = i_self.getUrl() || "";

		if (Ext.isObject(s_url)) {
			s_url = s_url.load || s_url.get;
		}

		var o_storeConfig = Ext.applyIf({}, {
			remoteSort: true,
			pageSize: 100,
			autoLoad: false,
			idProperty: i_self.getIdProperty(),
			proxy: {
				url: s_url || "",
				type: "ux.buffer"
			},
			fields: a_fields,
			listeners: {
				load: {
					fn: function(i_store, a_records) {

						a_records = Ext.Array.from(a_records);

						if (a_records.length > 0) {

							var i_record = a_records[0];
							i_self.loadRecord(i_record);
						}
					}
				}
			}
		});

		var i_store = Ext.create("Ext.ux.buffer.Store", o_storeConfig);
		var i_model = i_store.getModel();
		var i_record = i_model.create({});

		i_self.setStore(i_store);
		i_self.loadRecord(i_record);
	},

	addHandler: function() {

		var i_self = this;
		var i_form = i_self.getForm();
		var i_monitor = i_form.getFields();

		Ext.Array.each(i_monitor.items, function(i_field) {

			i_field.on({
				specialkey: "onSpecialKey"
			});
		});
	},

	load: function(o_options) {

		var i_self = this;
		var i_store = i_self.getStore();
		var i_proxy = i_store.getProxy();
		if (o_options) {
			i_proxy.setExtraParams(o_options);
		}
		i_store.load();
	},

	save: function(f_callback) {

		f_callback = f_callback || Ext.emptyFn;

		var i_self = this;
		var i_controller = i_self.getController();
		i_controller.onSave(function(b_success) {
			f_callback(b_success);
		});
	}
});
