Ext.define("Portfolio.designer.ui.domainModelProperties", {

	extend: "Ext.window.Window",

	alias: [
		"widget.ip2DomainModelProperties"
	],

	title: ip2.i18n("properties"),

	width: 800,

	height: 600,

	layout: {
		type: "fit"
	},

	resizable: false,

	modal: true,

	config: {
		designer: null,
		proxyForm: null,
		propertyForm: null,
		requireManager: null,
		baseDatatypeManager: null,
		languageGrid: null,
		tabpanel: null,
		mainForm: null
	},

	requires: [
		"Portfolio.designer.ui.require.view.Manager",
		"Portfolio.designer.ui.domainModelBaseDatatypeManager",
		"Portfolio.designer.ui.domainModelLanguageGrid"
	],

	initComponent: function() {

		var i_self = this;

		i_self.buttons = i_self.createButtons();

		i_self.callParent();

		i_self.add(i_self.createLayout());

		var i_mainForm = i_self.getMainForm().getForm();

		i_mainForm.checkValidity();
	},

	createLayout: function() {

		var i_self = this;
		var i_designer = i_self.getDesigner();

		var o_model = i_designer.model;
		var o_proxy = o_model.proxy || {};

		o_proxy.portfolio = o_proxy.hasOwnProperty("portfolio") ? o_proxy.portfolio : true;

		var o_reader = o_proxy.reader || {
			type: "json",
			rootProperty: "rows",
			totalProperty: "totalRows"
		};

		var o_writer = o_proxy.writer || {
			type: "json",
			writeAllFields: false
		};

		var o_actions = o_proxy.actionMethods || {
			create: "POST",
			read: "GET",
			update: "POST",
			destroy: "POST"
		};

		var s_type = o_proxy.xtype || "Ext.data.proxy.Ajax";

		Ext.applyIf(o_model, {
			generate: {
				tables: false,
				views: true,
				constraints: true,
				primaryKey: true
			}
		});

		var a_items = [];

		var i_propertyForm = Ext.widget("form", {
			border: false,
			bodyPadding: 10,
			layout: "anchor",
			autoScroll: true,
			defaults: {
				xtype: "textfield",
				labelWidth: 200,
				anchor: "100%"
			},
			items: [
				{
					fieldLabel: ip2.i18n("modelLibrary"),
					name: "name",
					value: o_model.name,
					allowBlank: false,
					listeners: {
						afterrender: {
							fn: function(i_field) {
								i_field.focus(false, 500);
							}
						},
						blur: {
							fn: function(i_field) {

								var value = i_field.getValue();

								var initValue = i_field.initialConfig.value || "";

								if (value != initValue) {

									Ext.Ajax.request({
										url: i_designer.serviceProxy + "?action=checkObject&lib=QSYS&obj=" + value + "&objType=*LIB",
										success: function (i_response) {

											var o_result = Ext.decode(i_response.responseText);

											if (o_result.success) {

												ip2.messageBox({
													title: ip2.i18n("warning"),
													message: Ext.String.format(ip2.i18n("modelLibraryAlreadyExists"), value),
													yesText: ip2.i18n({
														da: "Ok",
														en: "OK"
													}),
												});
											}
										}
									});
								}
							}
						}
					}
				},
				{
					xtype: "i18n-textfield",
					fieldLabel: ip2.i18n("title"),
					name: "title",
					asJSON: true,
					value: o_model.title,
					model: o_model,
					allowBlank: false
				},
				{
					fieldLabel: ip2.i18n({
						da: "Header farve",
						en: "Header color"
					}),
					name: "header",
					value: o_model.header || "#cbd0d5",
					allowBlank: false,
					xtype: "hsvwheelfield"
				},
				{
					fieldLabel: ip2.i18n({
						da: "Teskst farve",
						en: "Text color"
					}),
					name: "text",
					value: o_model.text || "000000",
					allowBlank: false,
					xtype: "hsvwheelfield"
				},
				{
					fieldLabel: ip2.i18n({
						da: "Default ccsid",
						en: "Default ccsid"
					}),
					name: "ccsid",
					value: o_model.ccsid || "",
					allowBlank: true
				},
				{
					fieldLabel: ip2.i18n("domainModelPrefix"),
					name: "prefix",
					value: o_model.prefix || "",
					allowBlank: true,
					hidden: true
				},
				{
					xtype: "fieldset",
					title: ip2.i18n({
						da: "Opret rettigheder",
						en: "Create permission"
					}),
					defaults: {
						xtype: "checkbox",
						labelWidth: 139,
						anchor: "100%"
					},
					items: [
						{
							fieldLabel: ip2.i18n({
								da: "Tabeller",
								en: "Tables"
							}),
							name: "tables",
							checked: o_model.generate.tables
						},
						{
							fieldLabel: ip2.i18n({
								da: "Views",
								en: "Views"
							}),
							name: "views",
							checked: o_model.generate.views
						},
						{
							fieldLabel: ip2.i18n({
								da: "Primær Nøgle",
								en: "Primary Key"
							}),
							name: "primaryKey",
							checked: o_model.generate.primaryKey
						},
						{
							fieldLabel: ip2.i18n({
								da: "Constrains",
								en: "Constrains"
							}),
							name: "constraints",
							checked: o_model.generate.constraints
						},
						{
							fieldLabel: ip2.i18n({
								da: "Verison 2",
								en: "Verison 2"
							}),
							name: "version",
							checked: o_model.generate.version
						}
					]
				}
			]
		});

		var i_requireManager = Ext.widget("designer.ui.require.manager", {
			designer: i_designer,
			title: ip2.i18n({
				da: "Requires",
				en: "Requires"
			})
		});

		var i_baseDatatypeManager = Ext.create("Portfolio.designer.ui.domainModelBaseDatatypeManager", {
			designer: i_designer
		});

		var i_languageGrid = Ext.create("Portfolio.designer.ui.domainModelLanguageGrid", {
			designer: i_designer
		});

		var i_proxyTypeStore = Ext.create("Ext.data.Store", {
			fields: [
				{
					name: "key",
					type: "string"
				},
				{
					name: "value",
					type: "auto"
				},
				{
					name: "actions",
					type: "auto"
				}
			],
			autoLoad: true,
			data: [
				{
					key: "Ajax",
					value: "Ext.data.proxy.Ajax",
					values: {
						limitParam: "limit",
						create: "POST",
						read: "GET",
						update: "POST",
						destroy: "POST"
					}
				},
				{
					key: "Rest",
					value: "Ext.data.proxy.Rest",
					values: {
						limitParam: "size",
						create: "POST",
						read: "GET",
						update: "PUT",
						destroy: "DELETE"
					}
				}
			]
		});

		var i_storeMethods = Ext.create("Ext.data.Store", {
			fields: [
				{
					name: "key",
					type: "string"
				},
				{
					name: "value",
					type: "auto"
				}
			],
			autoLoad: true,
			data: [
				{
					key: "POST",
					value: "POST"
				},
				{
					key: "GET",
					value: "GET"
				},
				{
					key: "PUT",
					value: "PUT"
				},
				{
					key: "PATCH",
					value: "PATCH"
				},
				{
					key: "DELETE",
					value: "DELETE"
				}
			]
		});

		var i_storeModes = Ext.create("Ext.data.Store", {
			fields: [
				{
					name: "key",
					type: "string"
				},
				{
					name: "value",
					type: "auto"
				}
			],
			autoLoad: true,
			data: [
				{
					key: "json",
					value: "json"
				},
				{
					key: "memory",
					value: "memory"
				}
			]
		});

		var i_proxyTypeField = Ext.widget("combobox", {
			xtype: "combobox",
			name: "xtype",
			fieldLabel: "Proxy type",
			store: i_proxyTypeStore,
			value: o_proxy.xtype || "Ext.data.proxy.Ajax",
			displayField: "key",
			valueField: "value",
			editable: false,
			listeners: {
				select: {
					fn: function(i_field, i_selected) {

						var i_proxyPanel = i_self.getProxyForm();
						var i_form = i_proxyPanel.getForm();
						var o_values = Ext.apply({}, i_selected.get("values"));

						i_form.setValues(o_values);
					}
				}
			}
		});

		var i_proxyForm = Ext.widget("form", {
			border: false,
			bodyPadding: 10,
			layout: "anchor",
			autoScroll: true,
			items: [
			{
				xtype: "fieldset",
				title: "General",
				defaults: {
					xtype: "textfield",
					labelWidth: 140,
					anchor: "100%"
				},
				items: [
					i_proxyTypeField,
					{
						fieldLabel: ip2.i18n("url"),
						name: "url",
						value: o_proxy.url,
						allowBlank: false
					},
					{
						fieldLabel: "Limit name",
						name: "limitParam",
						value: o_proxy.limitParam || "limit",
						allowBlank: false
					},
					{
						fieldLabel: "Portfolio services",
						name: "portfolio",
						xtype: "checkbox",
						value: o_proxy.portfolio
					}
				]
			},
			{
				xtype: "fieldset",
				title: "Reader",
				defaults: {
					xtype: "textfield",
					labelWidth: 139,
					anchor: "100%"
				},
				items: [
					{
						xtype: "combobox",
						name: "readertype",
						fieldLabel: "Type",
						store: i_storeModes,
						value: o_reader.type,
						displayField: "key",
						valueField: "value"
					},
					{
						fieldLabel: "Root Property",
						name: "rootProperty",
						value: o_reader.rootProperty,
						allowBlank: false
					},
					{
						fieldLabel: "Total Property",
						name: "totalProperty",
						value: o_reader.totalProperty,
						allowBlank: false
					}
				]
			},
			{
				xtype: "fieldset",
				title: "Writer",
				defaults: {
					xtype: "textfield",
					labelWidth: 139,
					anchor: "100%"
				},
				items: [
					{
						xtype: "combobox",
						name: "writertype",
						fieldLabel: "Type",
						store: i_storeModes,
						value: o_writer.type,
						displayField: "key",
						valueField: "value"
					}
				]
			},
			{
				xtype: "fieldset",
				title: "CRUD methods",
				defaults: {
					xtype: "combobox",
					store: i_storeMethods,
					value: s_type,
					displayField: "key",
					valueField: "value",
					editable: false,
					labelWidth: 139,
					anchor: "100%"
				},
				items: [
					{
						fieldLabel: "Create",
						name: "create",
						value: o_actions.create
					},
					{
						fieldLabel: "Read",
						name: "read",
						value: o_actions.read
					},
					{
						fieldLabel: "Update",
						name: "update",
						value: o_actions.update
					},
					{
						fieldLabel: "Destroy",
						name: "destroy",
						value: o_actions.destroy
					}
				]
			},
			{
				xtype: "fieldset",
				title: ip2.i18n("eventHandlerAPI"),
				defaults: {
					xtype: "textfield",
					labelWidth: 139,
					anchor: "100%"
				},
				items: [{
					fieldLabel: ip2.i18n("programName"),
					name: "eventHandlerAPI",
					value: o_model.API.eventHandler,
					allowBlank: true
				}]
			}]
		});

		var i_tabpanel = Ext.widget("tabpanel", {
			defaults: {
				layout: {
					type: "fit"
				}
			},
			items: [
				{
					title: ip2.i18n("properties"),
					items: i_propertyForm
				},
				i_requireManager,
				{
					title: ip2.i18n("baseDatatypes"),
					items: i_baseDatatypeManager
				},
				{
					title: ip2.i18n("USRLNG"),
					items: i_languageGrid
				},
				{
					title: ip2.i18n("proxy"),
					items: i_proxyForm
				}
			]
		});

		i_self.setPropertyForm(i_propertyForm);
		i_self.setProxyForm(i_proxyForm);
		i_self.setRequireManager(i_requireManager);
		i_self.setBaseDatatypeManager(i_baseDatatypeManager);
		i_self.setLanguageGrid(i_languageGrid);
		i_self.setTabpanel(i_tabpanel);

		a_items.push(i_tabpanel);

		var i_mainForm = Ext.widget("form", {
			items: a_items,
			layout: "fit",
			itemId: "mainForm",
			listeners: {
				dirtychange: {
					fn: function(i_form, b_dirty) {

						var i_button = i_self.down("#btnok");
						var b_valid = i_form.isValid();

						if (b_valid) {
							if (i_button) {
								i_button[b_dirty ? "enable" : "disable"]();
							}
						}
					}
				},
				validitychange: {
					fn: function(i_form, b_valid) {

						var i_button = i_self.down("#btnok");

						if (i_button) {
							if (b_valid) {
								i_form.fireEvent("dirtychange", i_form, i_form.isDirty());
							}
							else {
								i_button.disable();
							}
						}
					}
				},
				languagechange: {
					fn: function(i_languageGrid, b_changed) {

						var i_mainForm = i_languageGrid.up("#mainForm");
						var b_valid = i_mainForm.isValid();
						if (b_valid) {
							if (!i_mainForm.isDirty()) {
								i_mainForm.fireEvent("dirtychange", i_mainForm, b_changed);
							}
						}
					}
				},
				basedatatypechanged: {
					fn: function(i_basegrid, b_changed) {

						var i_mainForm = i_basegrid.up("#mainForm");
						var b_valid = i_mainForm.isValid();
						if (b_valid) {
							if (!i_mainForm.isDirty()) {
								i_mainForm.fireEvent("dirtychange", i_mainForm, b_changed);
							}
						}
					}
				}
			}
		});

		i_self.setMainForm(i_mainForm);

		return i_mainForm;
	},

	promptSaveChanges: function(f_callback) {

		var i_self = this;

		f_callback = f_callback || Ext.emptyFn;

		ip2.messageBox({
			title: ip2.i18n("saveChanges"),
			message: ip2.i18n("doYouWantToChange"),
			yesText: ip2.i18n({
				da: "Ja",
				en: "Yes"
			}),
			noText: ip2.i18n({
				da: "Nej",
				en: "No"
			}),
			yesFn: function () {
				if (i_self.doSave()) {
					f_callback();
				}
			},
			noFn: function () {
				f_callback();
			}
		});
	},

	createButtons: function() {

		var i_self = this;

		var a_buttons = [];

		var i_buttonOk = Ext.widget("button", {
			text: ip2.i18n("ok"),
			itemId: "btnok",
			disabled: true,
			handler: function() {
				if (i_self.doSave()) {
					var i_designer = i_self.getDesigner();
					i_designer.fireEvent("statechange", i_designer);
					i_self.close();
				}
			}
		});

		var i_buttonCancel = Ext.widget("button", {
			text: ip2.i18n("cancel"),
			itemId: "btncancel",
			handler: function() {

				var i_form = i_self.getMainForm();
				if (i_form.isValid() && i_form.isDirty()) {
					i_self.promptSaveChanges(function() {
						i_self.close();
					});
				}
				else {
					i_self.close();
				}
			}
		});

		a_buttons.push(i_buttonOk);
		a_buttons.push(i_buttonCancel);

		return a_buttons;
	},

	doSave: function() {

		var i_self = this;
		var i_designer = i_self.getDesigner();
		var o_model = i_designer.model;

		// save entity properties
		var i_propertForm = i_self.getPropertyForm().getForm();
		var o_propertyValues = i_propertForm.getFieldValues();

		o_model.navigator = o_model.navigator || {
			system: ""
		};

		Ext.Object.each(o_propertyValues, function(s_key) {
			switch (s_key) {
				case "system":
					o_model.navigator.system = o_propertyValues[s_key];
					break;
				default:
					o_model[s_key] = o_propertyValues[s_key];
					break;
			}
		});

		delete o_model.tables;
		delete o_model.views;
		delete o_model.primaryKey;
		delete o_model.constraints;

		o_model.generate = Ext.apply({}, {
			tables: o_propertyValues.tables,
			views: o_propertyValues.views,
			primaryKey: o_propertyValues.primaryKey,
			constraints: o_propertyValues.constraints,
			version: o_propertyValues.version
		});

		// save proxy properties
		var i_proxyForm = i_self.getProxyForm().getForm();

		var o_proxy = o_model.proxy || {
			url: ""
		};

		var o_api = o_model.API || {
			eventHandler: "",
			insert: "",
			remove: ""
		};

		var o_proxyValues = i_proxyForm.getFieldValues();

		Ext.apply(o_api, {
			eventHandler: o_proxyValues.eventHandlerAPI,
			insert: o_proxyValues.defaultInsertAPI,
			remove: o_proxyValues.defaultRemoveAPI
		});

		var o_reader = Ext.apply({}, {
			xtype: o_propertyValues.xtype,
			type: o_proxyValues.readertype,
			rootProperty: o_proxyValues.rootProperty,
			totalProperty: o_proxyValues.totalProperty
		});

		var o_writer = {
			type: o_proxyValues.writertype,
			writeAllFields: false
		};

		var o_actions = {
			create: o_proxyValues.create,
			read: o_proxyValues.read,
			update: o_proxyValues.update,
			destroy: o_proxyValues.destroy
		};

		// save base datatypes

		var o_types = i_self.getDesigner().normal.types;
		var o_return = {};
		var i_grid = i_self.getBaseDatatypeManager().down("ip2DomainModelBaseDatatypeGrid");
		var i_store = i_grid.getStore();

		var a_records = i_store.getRange();

		Ext.Array.each(a_records, function(i_record) {

			var s_name = "";
			var o_data = i_record.getData();
			var o_type = {};

			var o_template = o_types[o_data.type] || Ext.apply({}, {
				properties: {}
			});

			Ext.Object.each(o_data, function(s_key, value) {

				switch (s_key) {
					case "name":
						s_name = value;
						break;
					case "was":
						if (value.length > 0) {
							o_type[s_key] = value;
						}
						break;
					case "type":
						o_type[key] = (o_data.len > 0) ? value + "(" + o_data.len + ")" : value;
						break;
					case "drop":
					case "len":
						break;
					default:

						Ext.Object.each(o_template, function(s_property, o_value) {
							if (o_value.name == s_key) {
								o_type[s_key] = value;
								return false;
							}
						});

						break;
				}
			});

			o_return[s_name] = Ext.apply({}, o_type);
		});

		o_model.types = o_return;

		// save languages
		var o_languages = Ext.apply({}, o_model.languages);

		o_model.languages = {};
		i_store = i_self.getLanguageGrid().getStore();

		a_records = i_store.getRange();

		Ext.Array.each(a_records, function(i_record) {
			var o_language = {};

			var s_language = i_record.get("code");

			if (o_languages.hasOwnProperty(s_language)) {
				o_language = o_languages[s_language];
			}
			else {
				o_language = {
					text: {}
				};
			}

			o_model.languages[s_language] = o_language;
		});

		var a_require = i_self.getRequireManager().doSave();
		o_model.require = a_require;

		if (a_require.length === 0) {
			delete o_model.require;
		}

		Ext.apply(o_proxy, {
			url: o_proxyValues.url,
			portfolio: o_proxyValues.portfolio,
			reader: o_reader,
			write: o_writer,
			actionMethods: o_actions,
			xtype: o_proxyValues.xtype,
			limitParam: o_proxyValues.limitParam
		});

		Ext.apply(o_model, {
			proxy: o_proxy,
			API: o_api
		});

		i_designer.model = o_model;

		return true;
	}
});
