Ext.define("Portfolio.dynapp.ui.table.Editor", {

	extend: "Ext.window.Window",

	alias: "widget.dynapp.ui.table.editor",

	layout: "fit",

	viewModel: {
		type: "dynapp.detail"
	},

	controller: "dynapp.table",

	type: "",
	edit: true,

	alternateClassName: [
		"Ext.dynapp.ui.table.Editor"
	],

	requires: [
		"Portfolio.dynapp.controller.Table",
		"Portfolio.dynapp.viewmodel.Detail"
	],


	initComponent: function() {

		var i_self = this;
		i_self.callParent();

		var i_controller = i_self.getController();
		if (!i_self.record) {
			var i_model = i_controller.getModel(i_self.type);
			var i_record = i_model.create({});
			i_self.record = i_record;
		}

		var i_viewModel = i_self.getViewModel();
		i_viewModel.setData({
			grid: i_self.grid,
			record: i_self.record
		});

		i_self.add(i_self.createLayout(i_self.type));

		return i_self;
	},

	getValue: function() {

		var i_self = this;
		var i_form = i_self.down("form").getForm();
		var o_values = i_form.getFieldValues();
		return o_values;
	},

	createLayout: function(s_type) {

		var i_self = this;
		var o_options = i_self.options;
		var i_controller = i_self.getController();
		var i_form = Ext.widget("form", {
			layout: "anchor",
			bodyPadding: 5,
			trackResetOnLoad: true,
			defaults: {
				anchor: "100%",
				lableWidth: 150
			},
			items: i_controller.getFields(s_type, o_options.library),
			buttons: i_self.createButtons()
		});

		i_form.on({
			dirtychange: {
				fn: function(i_form, b_dirty) {
					var i_button = i_form.owner.down("#btn-save");
					if (i_button) {
						if (!b_dirty) {
							i_button.disable();
						}
						else {
							i_button.enable();
						}
					}
				}
			},
			validitychange: {
				fn: function(i_form, b_valid) {
					var i_button = i_form.owner.down("#btn-save");
					if (i_button) {
						if (!b_valid) {
							i_button.disable();
						}
						else {
							var b_dirty = i_form.isDirty();
							if (b_dirty) {
								i_form.fireEvent("dirtychange", i_form, b_dirty);
							}
						}
					}
				}
			}
		});

		return i_form;
	},

	createButtons: function() {

		var i_self = this;
		var a_buttons = [
			{
				xtype: "button",
				text: "Save",
				itemId: "btn-save",
				handler: "onSave",
				disabled: true
			},
			{
				xtype: "button",
				text: "Close",
				itemId: "btn-close",
				handler: function(item) {
					i_self.close();
				}
			}
		];
		return a_buttons;
	}
});
