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

	extend: "Ext.panel.Panel",

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

	layout: "fit",

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

	controller: "dynapp.gridpanel",

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

	requires: [
		"Portfolio.dynapp.controller.Grid",
		"Portfolio.dynapp.viewmodel.ColumnProperties"
	],

	initComponent: function() {

		var i_self = this;
		i_self.callParent();

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

		i_self.add(i_self.createLayout());

		return i_self;
	},

	createLayout: function() {

		var i_self = this;
		var o_options = i_self.grid.options;
		var i_form = Ext.widget("form", {
			layout: "fit",
			trackResetOnLoad: true,
			bodyPadding: 5,
			defaults: {
				anchor: "100%"
			},
			items: [
				{
					xtype: "acetextarea",
					hideLabel: true,
					name: "plugin",
					itemId: "editor-plugin",
					anchor: "100%",
					value: o_options.srcPlugin || "",
					validator: function(value) {

						var s_return = true;
						if (value) {
							var i_regexNewLine = new RegExp("\r?\n|\r", "g");
							var i_regexTab = new RegExp("\t", "g");
							var s_sanitized = value.replace(i_regexNewLine, "");
							var s_sanitized = s_sanitized.replace(i_regexTab, "");
							var b_valid = Ext.decode(s_sanitized, true);
							if (!b_valid) {
								s_return = "This needs to be valid json";
							}
						}

						return s_return;
					},
					listeners: {
						afterrender: {
							fn: function(item) {
								var i_editor = item;
								item.on({
									editorready: {
										fn: function(item) {
											setTimeout(function() {
												i_editor.getEditor().focus(false, 100);
											}, 100);
										},
										single: true
									}
								});
							}
						}
					}
				}
			],
			listeners: {
				validitychange: {
					fn: function(i_form, b_valid) {
						var i_open = i_self.down("#btn-save");
						if (i_open) {
							if (b_valid) {
								i_open.enable();
							}
							else {
								i_open.disable();
							}
						}
					}
				}
			}
		});

		return i_form;
	},

	isDirty: function() {

		var i_self = this;
		var i_form = i_self.down("form");
		return i_form.isDirty();
	},

	isValid: function() {

		var i_self = this;
		var i_form = i_self.down("form");
		return i_form.isValid();
	},

	getValue: function() {

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