Ext.define("Portfolio.dynapp.controller.Grid", {

	extend: "Ext.app.ViewController",

	alias: "controller.dynapp.gridpanel",

	alternateClassName: [
		"Ext.dynapp.controller.Grid"
	],

	onAfterRender: function() {

		var i_controller = this;
		var i_grid = i_controller.getView();
		var i_menu = i_grid.headerCt.getMenu();

		i_menu.on("beforeshow", function (item) {

			var a_items = i_grid.createColumnMenu(item.ownerCmp);

			var n_length = i_menu.items.getRange().length;

			if (n_length == 4) {

				var i_separator = Ext.widget("menuseparator", {});
				a_items.unshift(i_separator);
			}

			var i_columnItem = i_menu.child("#columnItem");
			var i_descItem = i_menu.child("#descItem");

			var i_deleteItem = i_menu.child("#bntDeleteColumn");
			var i_editItem = i_menu.child("#bntEditColumn");
			var i_addeItem = i_menu.child("#bntAddColumn");

			var n_index = i_menu.items.findIndexBy(function(i_item) {
				return i_item.itemId == "descItem";
			});

			if (i_deleteItem) {
				i_menu.remove(i_deleteItem);
			}

			if (i_editItem) {
				i_menu.remove(i_editItem);
			}

			if (i_addeItem) {
				i_menu.remove(i_addeItem);
			}
			if (n_length == 4) {
				i_menu.insert(n_index + 1, a_items);
			}
			else {
				i_menu.insert(n_index + 2, a_items);
			}
		});
	},

	onSortChange: function(header, column, direction) {

		var i_controller = this;
		var i_grid = i_controller.getView();
		var i_toolbar = i_grid.getFilterBar();
		if (i_toolbar) {
			i_toolbar.sortChange(column);
		}
	},

	onEdit: function(i_view, i_record) {

		var i_controller = this;
		var i_grid = i_controller.getView();
		var o_options = i_grid.options;
		var i_model = i_record.store.getModel();

		var a_fields = i_record.getFields();
		Ext.Array.each(a_fields, function(i_field) {
			Ext.Array.each(i_grid.fields, function(o_field) {
				if (o_field.name == i_field.name) {
					i_field.plugin = o_field.plugin;
				}
			});
		});

		if (ip2.isAccessible("app.dynapp.data.update") ||
			ip2.isAccessible("app.dynapp.data.read") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".update") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".read") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".table." + o_options.file + ".update") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".table." + o_options.file + ".read")
			) {
			if (i_record.dirty) {
				i_record.reject(true);
			}
			var i_window = Ext.widget("dynapp.detail", {
				title: "Edit: " + i_record.get(i_record.idProperty),
				width: 800,
				height: 600,
				record: i_record,
				options: o_options,
				model: i_model,
				grid: i_grid,
				uid: i_grid.uid,
				action: "edit"
			});
			i_window.show();
		}
	},

	onAdd: function() {

		var i_controller = this;
		var i_grid = i_controller.getView();
		var o_options = i_grid.options;
		var i_store = i_grid.getStore();
		var i_model = i_store.getModel();
		var i_record = i_model.create();

		var i_window = Ext.widget("dynapp.detail", {
			title: "New: ",
			width: 800,
			height: 600,
			record: i_record,
			model: i_model,
			options: o_options,
			grid: i_grid,
			action: "add"
		});

		i_window.show();
	},

	onItemMenu: function(i_view, i_record, item, index, e) {

		var i_controller = this;
		var i_grid = i_controller.getView();
		var i_store = i_grid.getStore();
		var o_options = i_grid.options;
		var a_coords = e.getXY();
		e.preventDefault();

		var a_items = [];

		if (ip2.isAccessible("app.dynapp.data.update") ||
			ip2.isAccessible("app.dynapp.data.read") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".update") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".read") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".table." + o_options.file + ".update") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".table." + o_options.file + ".read")
			) {
			a_items.push({
				xtype: "menuitem",
				text: ip2.i18n({
					da: "Redigér",
					en: "Edit"
				}),
				iconCls: "pf-edit",
				handler: function() {
					i_controller.onEdit(i_grid.getView(), i_record);
				}
			});
		}

		if (ip2.isAccessible("app.dynapp.data.delete") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".delete") ||
			ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".table." + o_options.file + ".delete")
			) {
			a_items.push({
				xtype: "menuitem",
				text: ip2.i18n({
					da: "Slet",
					en: "Delete"
				}),
				iconCls: "pf-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 () {
							i_controller.onDelete(i_record);
						},
						yesText: ip2.i18n({
							da: "Ja",
							en: "Yes"
						}),
						noText: ip2.i18n({
							da: "Nej",
							en: "No"
						})
					});
				}
			});
		}

		if (a_items.length > 0) {
			var i_menu = Ext.widget("menu", {
				items: a_items
			});

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

	onSave: function() {

		var i_controller = this;
		var i_window = i_controller.getView();
		var i_form = i_window.down("form").getForm();
		var i_viewModel = i_controller.getViewModel();

		var i_grid = i_viewModel.get("grid");
		var i_record = i_viewModel.get("rec");
		var i_model = i_window.model;
		var o_options = i_grid.options;
		var i_store = i_grid.getStore();

		var a_fields = i_form.getFields().items;
		var o_row = {};
		var o_props = {};
		var b_hasProp = i_window.props.length > 0;

		Ext.Array.each(a_fields, function(i_field) {
			if (b_hasProp) {
				if (i_field.propertyHost) {
					if (o_props[i_field.propertyHost]) {
						o_props[i_field.propertyHost][i_field.name] = i_field.getValue();
					}
					else {
						o_props[i_field.propertyHost] = {};
						o_props[i_field.propertyHost][i_field.name] = i_field.getValue();
					}
				}
				else {
					o_row[i_field.name] = i_field.xtype == "datefield" ? i_field.getSubmitValue() : i_field.getValue();
				}
			}
			else {
				o_row[i_field.name] = i_field.xtype == "datefield" ? i_field.getSubmitValue() : i_field.getValue();
			}
		});

		if (b_hasProp) {
			var a_props = Ext.Object.getKeys(o_props);
			Ext.Array.each(a_props, function(s_key) {
				o_row[s_key] = o_props[s_key];
			});
		}

		var o_data = {
			row: o_row
		};

		if (i_window.action == "edit") {
			o_data.action = "updateRow";
			o_data.id = o_row[i_model.idProperty];
			delete o_row[i_model.idProperty];
		}
		else {
			o_data.action = "insertRow";
			delete o_row[i_model.idProperty];
		}

		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 {
					i_window.close();
					if (!i_grid.isDestroyed) {
						i_store.load();
					}
				}
			}
		});
	},

	onDelete: function(i_record) {

		var i_controller = this;
		var i_grid = i_controller.getView();
		var o_options = i_grid.options;
		var i_store = i_grid.getStore();
		var i_model = i_store.getModel();
		var o_data = i_record.getData();

		var o_params = {
			action: "deleteRow",
			id: o_data[i_model.idProperty]
		};
		var s_msg = ip2.i18n({
			da: "Sletter...",
			en: "Deleting..."
		});
		i_grid.setLoading(s_msg);
		Ext.Ajax.request({
			url: Portfolio.dynapp.util.Service.getPath(o_options),
			method: "POST",
			jsonData: o_params,
			success: function (response, request) {
				i_grid.setLoading(false);
				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 {
					i_store.load();
				}
			}
		});
	},

	onPluginSave: function() {

		var i_controller = this;
		var i_window = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var i_grid = i_viewModel.get("grid");

		var o_options = i_grid.options;
		var s_plugin = i_window.getValue();
		o_options.properties.plugin = s_plugin;
		var o_data = {
			action: "setProperty",
			schema: o_options.library,
			table: o_options.file,
			propName: "plugin",
			propValue: {
				src: s_plugin
			}
		};

		var s_msg = ip2.i18n({
			da: "Gemmer...",
			en: "Saving..."
		});
		i_window.setLoading(s_msg);

		Ext.Ajax.request({
			url: Portfolio.dynapp.util.Service.getPath(o_options),
			method: "POST",
			jsonData: o_data,
			success: function (response, request) {
				i_window.setLoading(false);
				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 {
					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);
						i_window.close();
					});
				}
			}
		});
	},

	onClose: function() {

		var i_controller = this;
		var i_window = i_controller.getView();
		i_window.close();
	}
});
