Ext.define("Portfolio.dynapp.ui.table.Manager", {
	extend: "Ext.window.Window",
	alias: "widget.dynapp.ui.table.manager",

	layout: "fit",

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

	controller: "dynapp.gridpanel",

	isSaved: false,

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

	requires: [
		"Portfolio.dynapp.controller.Grid",
		"Portfolio.dynapp.viewmodel.ColumnProperties",
		"Portfolio.dynapp.ui.table.Plugin",
		"Portfolio.dynapp.model.Relation",
		"Portfolio.dynapp.model.Affiliation"
	],

	uses: [
		"Portfolio.dynapp.ui.table.Editor",
	],

	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());

		i_self.on({
			beforeclose: {
				fn: function(item) {
					if (i_self.isDirty()) {
						var o_options = i_self.grid.options;
						var i_grid = i_self.grid;
						var i_relationStore = i_self.relations.getStore();
						var i_affliationStore = i_self.affiliations.getStore();
						var i_plugin = i_self.pluginPanel;
						var a_affliations = i_affliationStore.data.items;
						var a_relations = i_relationStore.data.items;
						var s_plugin = i_plugin.getValue();

						var a_result = [];

						Ext.Array.each(a_relations, function(i_record) {
							var o_data = i_record.data;
							delete o_data.id;
							o_data.table = o_data.table.split("/").pop();
							a_result.push(o_data);
						});

						i_self.saveRelations(a_result, function() {
							a_result = [];
							Ext.Array.each(a_affliations, function(i_record) {
								var o_data = i_record.data;
								delete o_data.id;
								a_result.push(o_data);
							});
							i_self.saveAffiliations(a_result, function() {
								i_self.savePlugin(s_plugin, function() {
									Portfolio.dynapp.util.Service.getMeta(o_options, function(o_meta) {
										o_options.properties = o_meta.properties;
										o_options.srcPlugin = o_meta.srcPlugin;
										i_grid.doApply(o_options, o_meta.fields);
									});
								});
							});
						});
					}
				}
			}
		});

		return i_self;
	},

	isDirty: function() {

		var i_self = this;
		var i_affliations = i_self.affiliations;
		var i_relations = i_self.relations;
		var i_plugin = i_self.pluginPanel;

		return i_affliations.isDirty() || i_relations.isDirty() || (i_plugin.isValid() && i_plugin.isDirty());
	},

	createLayout: function() {

		var i_self = this;
		var o_options = i_self.grid.options;

		var i_tabpanel = Ext.widget("tabpanel", {
			layout: "fit",
			flex: 1,
			items: [
				i_self.createRelations(i_self.grid.options),
				i_self.createAffiliations(i_self.grid.options),
				i_self.createPlugin()
			]
		});

		return i_tabpanel;
	},

	createPlugin: function() {

		var i_self = this;
		var i_grid = i_self.grid;
		var i_plugin = Ext.widget("dynapp.ui.table.plugin", {
			title: ip2.i18n({
				da: "Plugin",
				en: "Plugin"
			}),
			grid: i_grid,
			dirty: false,
			listeners: {
				activate: {
					fn: function(item) {

						var i_editor = item.down("#editor-plugin");
						if (i_editor && i_editor.getEditor()) {
							i_editor.getEditor().focus(false, 100);
						}
					}
				}
			}
		});

		i_self.pluginPanel = i_plugin;

		return i_plugin;
	},

	createRelations: function(o_options) {

		var i_self = this;
		var o_properites = o_options.properties;
		var i_store = Ext.create("Ext.data.Store", {
			model: "Portfolio.dynapp.model.Relation",
			autoLoad: true,
			proxy: {
				data: o_properites.relations,
				type: "memory"
			},
			listeners: {
				load: {
					fn: function(store, a_record) {

						if (i_self.relations && i_self.relations.originalValue == undefined) {
							var a_result = [];
							Ext.Array.each(a_record, function(i_record) {
								a_result.push(i_record.data);
							});
							var s_value = JSON.stringify(a_result);
							i_self.relations.originalValue = s_value;
						}
					}
				}
			}
		});

		var i_grid = Ext.widget("gridpanel", {
			title: ip2.i18n({
				da: "Relationer",
				en: "Relations"
			}),
			store: i_store,
			columns: [
				{ text: ip2.i18n({
					da: "Til tabel",
					en: "To table"
				}), dataIndex: "table", width: 150 },
				{ text: ip2.i18n({
					da: "Til skema",
					en: "To scheme"
				}), dataIndex: "schema", width: 150,
					renderer: function(value) {
						if (!value) {
							value = "*CURRENT";
						}
						return value;
					}
				},
				{ text: ip2.i18n({
					da: "Join",
					en: "Join"
				}), dataIndex: "join", flex: 1 }
			],
			listeners: {
				itemdblclick: {
					fn: function(i_view, i_record) {
						var i_editor = i_self.getEditor("relation", i_view, true, i_record);
						i_editor.show();
					}
				},
				itemcontextmenu: {
					fn: function(i_view, i_record, item, index, e) {
						i_self.getRowMenu("relation", i_view, i_record, e);
					}
				}
			},
			isDirty: function() {

				var i_grid = this;
				var i_store = i_grid.getStore();
				var a_records = i_store.data.items;
				var a_result = [];
				Ext.Array.each(a_records, function(i_record) {
					a_result.push(i_record.data);
				});
				var s_value = JSON.stringify(a_result);
				return s_value != i_grid.originalValue;
			}
		});

		var i_toolbar = i_self.getToolbar("relation", i_grid);

		i_grid.addDocked(i_toolbar);

		i_self.relations = i_grid;

		return i_grid;
	},

	createAffiliations: function(o_options) {

		var i_self = this;
		var o_properites = o_options.properties;
		var i_store = Ext.create("Ext.data.Store", {
			model: "Portfolio.dynapp.model.Affiliation",
			autoLoad: true,
			proxy: {
				data: o_properites.affiliations,
				type: "memory"
			},
			listeners: {
				load: {
					fn: function(store, a_record) {

						if (i_self.affiliations && i_self.affiliations.originalValue == undefined) {
							var a_result = [];
							Ext.Array.each(a_record, function(i_record) {
								a_result.push(i_record.data);
							});
							var s_value = JSON.stringify(a_result);
							i_self.affiliations.originalValue = s_value;
						}
					}
				}
			}
		});

		var i_grid = Ext.widget("gridpanel", {
			title: ip2.i18n({
				da: "Affiliationer",
				en: "Affiliations"
			}),
			store: i_store,
			columns: [
				{ text: ip2.i18n({
					da: "Navn",
					en: "Name"
				}), dataIndex: "name", width: 150 },
				{ text: ip2.i18n({
					da: "Url",
					en: "Url"
				}), dataIndex: "url", flex: 1 }
			],
			listeners: {
				itemdblclick: {
					fn: function(i_view, i_record) {
						var i_editor = i_self.getEditor("affiliation", i_view, true, i_record);
						i_editor.show();
					}
				},
				itemcontextmenu: {
					fn: function(i_view, i_record, item, index, e) {
						i_self.getRowMenu("affiliation", i_view, i_record, e);
					}
				}
			},
			isDirty: function() {

				var i_grid = this;
				var i_store = i_grid.getStore();
				var a_records = i_store.data.items;
				var a_result = [];
				Ext.Array.each(a_records, function(i_record) {
					a_result.push(i_record.data);
				});
				var s_value = JSON.stringify(a_result);
				return s_value != i_grid.originalValue;
			}
		});

		var i_toolbar = i_self.getToolbar("affiliation", i_grid);

		i_grid.addDocked(i_toolbar);

		i_self.affiliations = i_grid;

		return i_grid;
	},

	getEditor: function(s_type, i_grid, b_edit, i_record) {

		var i_self = this;
		var o_options = i_self.grid.options;
		var s_start = b_edit ? ip2.i18n({
			da: "Redigér ",
			en: "Edit"
		}) :
		ip2.i18n({
			da: "Ny ",
			en: "New "
		});
		var s_text = s_type == "relation" ?
		ip2.i18n({
			da: "relation",
			en: "relation"
		}) :
		ip2.i18n({
			da: "affiliation",
			en: "affiliation"
		});
		var i_editor = Ext.widget("dynapp.ui.table.editor", {
			title: s_start + s_text,
			width: 600,
			height: 400,
			type: s_type,
			edit: b_edit,
			options: o_options,
			grid: i_grid,
			record: i_record
		});

		return i_editor;
	},

	getRowMenu: function(s_type, i_grid, i_record, e) {

		var i_self = this;
		var a_coords = e.getXY();
		e.preventDefault();

		var i_menu = Ext.widget("menu", {
			items: [
				{
					text: ip2.i18n({
						da: "Redigér",
						en: "Edit"
					}),
					iconCls: "ip2-icon-edit",
					handler: function() {
						var i_editor = i_self.getEditor(s_type, i_grid, true, i_record);
						i_editor.show();
					}
				},
				{
					text: ip2.i18n({
						da: "Slet",
						en: "Delete"
					}),
					iconCls: "ip2-icon-delete",
					handler: function() {
						ip2.messageBox({
							icon: Ext.MessageBox.WARNING,
							title: ip2.i18n({
								da: "Slet..?",
								en: "Delete..?"
							}),
							closable: true,
							message: ip2.i18n({
								da: "Vil du slette denne række?",
								en: "Do you want to delete this record?"
							}),
							yesFn: function () {
								var i_store = i_grid.getStore();
								i_store.remove(i_record, true);
								i_store.fireEvent("removed", i_store, [i_record]);
							},
							yesText: ip2.i18n({
								da: "Ja",
								en: "Yes"
							}),
							noText: ip2.i18n({
								da: "Nej",
								en: "No"
							})
						});
					}
				}
			]
		});

		i_menu.showAt(a_coords[0], a_coords[1]);
	},

	getToolbar: function(s_type, i_grid) {

		var i_self = this;
		var i_toolbar = Ext.widget("toolbar", {
			dock: "top",
			items: [
				{
					xtype: "button",
					iconCls: "pf-add",
					text: ip2.i18n({
						da: "Tilføj",
						en: "Add"
					}),
					handler: function() {
						var i_editor = i_self.getEditor(s_type, i_grid, false);
						i_editor.show();
					}
				}
			]
		});
		return i_toolbar;
	},

	saveRelations: function(a_records, f_callback) {

		var i_self = this;
		var i_grid = i_self.grid;
		var o_options = i_grid.options;
		var o_data = {
			action: "setProperty",
			schema: o_options.library,
			table: o_options.file,
			propName: "relations",
			propValue: a_records
		};

		Ext.Ajax.request({
			url: Portfolio.dynapp.util.Service.getPath(o_options),
			method: "POST",
			jsonData: o_data,
			success: function (response, request) {
				var result = JSON.parse(response.responseText);
				if (result.success != undefined && !result.success) {
					ip2.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: result.message,
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						})
					});
				}
				else {
					f_callback();
				}
			}
		});
	},

	saveAffiliations: function(a_records, f_callback) {

		var i_self = this;
		var i_grid = i_self.grid;
		var o_options = i_grid.options;
		var o_data = {
			action: "setProperty",
			schema: o_options.library,
			table: o_options.file,
			propName: "affiliations",
			propValue: a_records
		};

		Ext.Ajax.request({
			url: Portfolio.dynapp.util.Service.getPath(o_options),
			method: "POST",
			jsonData: o_data,
			success: function (response, request) {
				var result = JSON.parse(response.responseText);
				if (result.success != undefined && !result.success) {
					ip2.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: result.message,
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						})
					});
				}
				else {
					f_callback();
				}
			}
		});
	},

	savePlugin: function(s_plugin, f_callback) {

		var i_self = this;
		var i_grid = i_self.grid;
		var o_options = i_grid.options;
		var o_data = {
			action: "setProperty",
			schema: o_options.library,
			table: o_options.file,
			propName: "plugin",
			propValue: {
				src: s_plugin
			}
		};

		Ext.Ajax.request({
			url: Portfolio.dynapp.util.Service.getPath(o_options),
			method: "POST",
			jsonData: o_data,
			success: function (response, request) {
				var result = JSON.parse(response.responseText);
				if (result.success != undefined && !result.success) {
					ip2.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: result.message,
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						})
					});
				}
				else {
					f_callback();
				}
			}
		});
	}
});
