Ext.define("Portfolio.designer.ui.save.view.Main", {
	extend: "Ext.window.Window",
	alias: "widget.designer.ui.save.view.main",

	layout: "fit",
	modal: true,

	config: {
		entity: "",
		dmd: "",
		entityTitle: "",
		form: null,
		tree: null,
		userpanel: null
	},

	requires: [
		"Portfolio.designer.ui.save.view.Tree",
		"Ext.ux.navigation.controller.UserRole",
		"Ext.ux.navigation.view.UserRolePanel"
	],

	initComponent: function() {

		var i_self = this;
		i_self.callParent();

		i_self.add(i_self.createLayout());

		return i_self;
	},

	createLayout: function() {

		var i_self = this;

		var i_tabpanel = Ext.widget("tabpanel", {
			layout: "fit"
		});

		var i_model;

		if (!Ext.ClassManager.isCreated("designer.ui.save")) {
			i_model = Ext.define("designer.ui.save", {
				extend: "Ext.data.Model",
				fields: [
					{ name: "id", type: "auto" },
					{ name: "APPICO", type: "string" },
					{ name: "dmd", type: "string" },
					{ name: "entity", type: "string" },
					{ name: "text", type: "auto" }
				],
				idProperty: "id"
			});
		}
		else {
			i_model = Ext.ClassManager.get("designer.ui.save");
		}

		var i_record = i_model.create({
			entity: i_self.getEntity(),
			dmd: i_self.getDmd(),
			text: i_self.getEntityTitle()
		});

		var i_iconpicker = Ext.widget({
			xtype: "ux.form.field.iconpicker",
			minChars: 1,
			fieldLabel: ip2.i18n({
				da: "Ikon",
				en: "Icon"
			}),
			name: "APPICO",
			allowBlank: true
		});

		var i_tree = Ext.widget("designer.ui.save.view.tree", {
			region: "west",
			layout: "fit",
			border: false,
			flex: 1,
			split: true
		});

		var i_userRolePanel = Ext.widget("userrolepanel", {
			region: "south",
			title: ip2.i18n({
				da: "Roller",
				en: "Roles"
			}),
			record: i_record,
			entity: "NAVMNUET00",
			flex: 1,
			border: false,
			split: true
		});

		var i_content = Ext.widget("panel", {
			layout: "border",
			border: false,
			items: [
				{
					xtype: "panel",
					flex: 1,
					layout: "border",
					region: "center",
					border: false,
					split: true,
					items: [
						{
							xtype: "panel",
							region: "center",
							layout: "anchor",
							bodyPadding: 5,
							border: false,
							flex: 1,
							defaults: {
								anchor: "100%"
							},
							items: [
								{
									xtype: "textfield",
									fieldLabel: ip2.i18n({
										da: "Entitet",
										en: "Entity"
									}),
									name: "entity",
									allowBlank: false,
									readOnly: true
								},
								{
									xtype: "textfield",
									fieldLabel: ip2.i18n({
										da: "DMD file",
										en: "DMD file"
									}),
									name: "dmd",
									allowBlank: false,
									readOnly: true
								},
								{
									xtype: "i18n-textfield",
									fieldLabel: ip2.i18n({
										da: "Title",
										en: "Title"
									}),
									name: "text",
									listeners: {
										afterrender: {
											fn: function(i_field) {
												i_field.focus(false, 10);
											},
											buffer: 250
										}
									}
								},
								i_iconpicker
							]
						},
						i_userRolePanel
					]
				},
				i_tree
			]
		});

		var i_form = Ext.widget("form", {
			layout: "fit",
			trackResetOnLoad: true,
			listeners: {
				validitychange: {
					fn: function(i_form, b_valid) {
						var i_save = i_self.down("#btn-save");
						if (i_save) {
							if (b_valid) {
								i_save.enable();
							}
							else {
								i_save.disable();
							}
						}
					}
				}
			},
			buttons: i_self.createButtons()
		});

		i_form.add(i_content);
		i_form.loadRecord(i_record);

		i_tabpanel.setActiveTab(0);

		i_self.setForm(i_form);
		i_self.setTree(i_tree);
		i_self.setUserpanel(i_userRolePanel);

		return i_form;
	},

	createButtons: function() {

		var i_self = this;
		var a_buttons = [
			{
				xtype: "button",
				text: ip2.i18n({
					da: "Gem",
					en: "Save"
				}),
				disabled: true,
				itemId: "btn-save",
				handler: function(i_button) {
					var s_msg = "";
					s_msg = ip2.i18n({
						da: "Gemmer...",
						en: "Saving..."
					});

					i_self.el.mask(s_msg);
					i_self.onSaveApp(function(o_result) {
						if (!o_result) {
							i_self.el.unmask();
						}
						else {
							var i_form = i_self.getForm();
							var i_userRolePanel = i_self.getUserpanel();

							var i_record = i_form.getRecord();
							i_record.set(i_record.idProperty, o_result.MNUMNUTKN);

							if (i_userRolePanel) {
								i_userRolePanel.record = i_record;
								i_userRolePanel.getController().doSave(function() {
									i_self.close();
								});
							}
						}
					});
				}
			},
			{
				xtype: "button",
				text: ip2.i18n({
					da: "Luk",
					en: "Close"
				}),
				itemId: "btn-close",
				handler: function() {
					i_self.close();
				}
			}
		];

		return a_buttons;
	},

	onSaveApp: function(f_callback) {

		var i_self = this;

		var i_form = i_self.getForm().getForm();
		var o_values = i_form.getFieldValues();
		var i_checked = i_self.getTree().getChecked()[0];

		var s_path = "/portfolio/ip2-run-dmd.js?" +  Ext.Object.toQueryString({
			entity: o_values.entity,
			dmd: o_values.dmd
		});

		var i_model = ip2.model({
			dmd: "dmd/portfolio.dmd",
			entityName: "NAVMNUET00",
			uiName: "portfolio",
			context: "form"
		});

		var i_record = i_model.create({
			MNUMNUTKN: 0,
			MNUPNTTKN: i_checked.get(i_checked.idProperty),
			MNUPROP: Ext.encode({
				title: o_values.text,
				icon: o_values.APPICO,
				url: s_path,
				__cid__: 3
			})
		});

		var o_keys = {};

		o_keys[i_record.idProperty] = i_record.get(i_record.idProperty);

		var o_batch = Ext.apply({}, {
			type: "upsert",
			dmd: "dmd/portfolio.dmd",
			entity: "NAVMNUET00",
			key: o_keys,
			row: i_record.getData()
		});

		Ext.Ajax.request({
			url: "/ip2-services/ip2dmdProxy.aspx",
			jsonData: {
				batch: [
					o_batch
				]
			},
			success: function (i_response, i_request) {

				var o_result = Ext.decode(i_response.responseText, true) || {
					success: false,
					batch: [{
						rows: []
					}]
				};

				Ext.applyIf(o_result, {
					success: false,
					batch: [{
						row: {}
					}]
				});

				if (!o_result.success) {

					ip2.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: o_result.message,
						yesFn: function() {
							f_callback(false);
						},
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						})
					});
				}
				else {
					if (o_result.success) {

						var a_rows = o_result.batch[0].row;

						f_callback(a_rows);
					}
				}
			}
		});
	}
});
