Ext.define("Portfolio.registry.util.Service", {

	singleton: true,

	base: {
		url: "/ip2-services/ip2Registry.aspx",
		name: "Portfolio.registry.model.Detail"
	},
	transaction: {
		url: "/ip2-services/ip2transaction.aspx"
	},

	config: {
		errorTpl: null
	},

	alternateClassName: [
		"Ext.registry.util.Service"
	],

	constructor: function(o_config) {

		var i_self = this;
		i_self.initConfig(o_config);

		var i_template = i_self.createErrorTemplate();
		i_self.setErrorTpl(i_template);
	},

	getPath: function(o_value) {

		var i_self = this;
		return Portfolio.registry.util.Service.transaction.url;
	},

	getTransactionUrl: function(o_options) {

		var i_self = this;
		var s_url = Portfolio.registry.util.Service.transaction.url;

		o_options = o_options || {};

		var a_path = [s_url];

		if (o_options.hasOwnProperty("library")) {
			a_path.push(o_options.library);
		}

		if (o_options.hasOwnProperty("file")) {
			a_path.push(o_options.file);
		}

		a_path.push("json");

		var s_result = a_path.join(".");

		return s_result;
	},

	getTransactionJson: function(o_options, s_type, a_records) {

		var o_json = {};

		var a_rows = [];

		Ext.Array.each(a_records, function(i_record) {
			a_rows.push(i_record.getData());
		});

		switch (s_type) {
			case "save":
			case "delete":
				Ext.apply(o_json, {
					rows: a_rows
				});
				break;
			default:
				break;
		}

		Ext.apply(o_json, {
			action: o_options.action,
			access: o_options.key
		});

		o_json[o_options.id] = o_options.idProperty;

		return o_json;
	},

	setDataAccess: function(o_options, s_type, a_records, f_callback) {

		var o_json = Portfolio.registry.util.Service.getTransactionJson(o_options, s_type, a_records);

		Ext.Ajax.request({
			url: Portfolio.registry.util.Service.getTransactionUrl(),
			jsonData: o_json,
			success: function (i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};
				f_callback(o_result);
			},
			failure: function() {
				var o_result = {};
				f_callback(o_result);
			}
		});
	},

	getJsonData: function(o_value, s_type, o_record, o_store) {

		var o_json = {};
		var s_registry = "";
		var a_path = [];

		o_value = o_value || {};

		switch (s_type) {

			case "get":
				Ext.apply(o_json, {
					action: "ip2registry.getNode",
					key: o_record.key
				});
				break;
			case "set":
				Ext.apply(o_json, {
					action: "ip2registry.setValue",
					key: o_record.key,
					value: o_record.value,
					meta: o_record.meta
				});
				break;
			case "setDataStore":
				Ext.apply(o_json, {
					action: "ip2registry.setDatastoreValue",
					key: o_record.key,
					value: o_record.value,
					datastore: o_store
				});
				break;
			case "getDataStore":
				Ext.apply(o_json, {
					action: "ip2registry.getDataStoreNode",
					key: o_record.key,
					datastore: o_store
				});
				break;
			case "single":
				Ext.apply(o_json, {
					action: "ip2registry.setValue",
					key: o_record.key,
					value: o_record.value
				});
				break;
			case "delete":
				Ext.apply(o_json, {
					action: "ip2registry.deleteNode",
					key: o_record.key
				});
				break;
			case "copy":
				Ext.apply(o_json, {
					action: "ip2registry.copyNode",
					from: o_record.from,
					to: o_record.to
				});
				break;
			case "move":
				Ext.apply(o_json, {
					action: "ip2registry.moveNode",
					from: o_record.from,
					to: o_record.to
				});
				break;
		}

		if (o_value.hasOwnProperty("library")) {
			a_path.push(o_value.library);
		}

		if (o_value.hasOwnProperty("file")) {
			a_path.push(o_value.file);
		}

		Ext.apply(o_json, {
			registry: a_path.join("/")
		});

		return o_json;
	},

	getModelName: function(o_value) {

		var i_self = this;
		var s_return = Portfolio.registry.util.Service.base.name;

		if (o_value.library && o_value.file) {
			s_return = [o_value.library, o_value.file].join("-");
		}

		return s_return;
	},

	getEditor: function(o_options, o_field, o_store) {

		var i_self = this;
		var i_field;
		var o_meta = o_field.meta;
		var o_properties = o_meta.properties;
		var o_plugin = o_meta.plugin;
		var s_name = o_field.key.split(".").pop();
		var s_label = o_properties.title ? o_properties.title : s_name.charAt(0) + s_name.slice(1);

		var o_config = {
			name: o_field.key,
			value: o_field.value,
			defaultLanguage: ip2.getUser().get("USRLNG") || "en",
			languages: wsh.getLanguages("portfolio")
		};

		var s_type = "textfield";
		var s_metatype = "varchar";

		if (o_properties.type) {
			s_metatype = o_properties.type;
		}
		switch (s_metatype){
			case "string":
			case "char":
			case "varchar":
				if (o_properties.len >= 40) {
					s_type = "textarea";
				}
				o_config = Ext.apply(o_config, {
					maxLength: o_properties.len || 30
				});
				break;
			case "integer":
			case "int":
			case "decimal":
			case "dec":
			case "float":
			case "smallint":
			case "bigint":
			case "numeric":
				s_type = "numberfield";
				var n_precision = 0;
				if (o_properties.prec) {
					n_precision = o_properties.prec;
				}
				else {
					if (s_metatype != "int" || s_metatype != "integer") {
						n_precision = 2;
					}
				}
				o_config = Ext.apply(o_config, {
					decimalPrecision: n_precision,
					decimalSeparator: Ext.util.Format.decimalSeparator,
					maxLength: o_properties.len || 30
				});
				break;
			case "timestamp":
				s_type = "isotimestampfield";
				break;
			case "date":
				s_type = "datefield";
				o_config = Ext.apply(o_config, {
					format: "d-m-Y",
					submitFormat: "Y-m-d"
				});
				break;
			case "bool":
				s_type = "checkbox";
				break;
			default :
				o_config = Ext.apply(o_config, {
					maxLength: o_properties.len || 30
				});
				break;
		}

		var o_evaled;
		var f_validator;

		if (o_plugin.src) {
			try {
				eval("o_evaled = " + o_plugin.src);
			}
			catch (err) {
				console.log("eval error check plugin if its valid");
				o_evaled = {};
			}
			if (o_evaled.xtype) {
				if (o_evaled.xtype.indexOf("i18n") != -1) {
					var a_languages = o_config.languages;
					if (a_languages.indexOf(o_config.defaultLanguage) != 0) {
						var n_index = a_languages.indexOf(o_config.defaultLanguage);
						var s_value = a_languages.splice(n_index, 1)[0];
						a_languages.unshift(s_value);
					}
				}
				s_type = o_evaled.xtype;
			}
			if (o_evaled.validator) {
				f_validator = o_evaled.validator;
				delete o_evaled.validator;
			}
			Ext.apply(o_config, o_evaled);
		}

		i_field = Ext.widget(s_type, o_config);

		if (o_evaled && f_validator) {
			i_field.getErrors = (function(f_old) {
				return function(value) {
					value = i_field.getValue();
					var a_errors = f_old.apply(this, [value]) || [];

					var s_error = f_validator.call(this, i_self._form.getForm(), value) || "";

					if (s_error) {
						a_errors.push(s_error);
					}

					return a_errors;
				};
			})(i_field.getErrors);
		}
		i_field.suspendCheckChange++;
		i_field.setValue(o_field.value);
		i_field.resetOriginalValue();
		i_field.suspendCheckChange--;
		return i_field;
	},

	getChildNodes: function(o_options, o_record, o_store, f_callback) {

		var o_json = Portfolio.registry.util.Service.getJsonData(o_options, "get", o_record, o_store);

		Ext.Ajax.request({
			url: Portfolio.registry.util.Service.getPath(),
			jsonData: o_json,
			success: function (i_response, request) {

				var a_result = Ext.decode(i_response.responseText, true) || [];

				Ext.Array.each(a_result, function(o_record) {

					var o_meta = o_record.meta || {
						properties: {},
						plugin: {
							src: ""
						}
					};
					o_record.meta = o_meta;
					if (!o_meta.properties) {
						o_meta.properties = Ext.apply({}, o_meta);
					}
					if (!o_meta.plugin) {
						o_meta.plugin = {
							src: ""
						};
					}
				});

				f_callback(a_result);
			},
			failure: function() {
				var a_result = [];
				f_callback(a_result);
			}
		});
	},

	getNode: function(o_options, o_record, o_store, f_callback) {

		var s_methode = "";

		if (o_store) {
			s_methode = "getDataStore";
		}

		var o_json = Portfolio.registry.util.Service.getJsonData(o_options, s_methode, o_record, o_store);

		Ext.Ajax.request({
			url: Portfolio.registry.util.Service.getPath(),
			jsonData: o_json,
			success: function (i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {
					userowselection: true,
					filters: []
				}

				f_callback(o_result);
			},
			failure: function() {
				var o_result = {};
				f_callback(o_result);
			}
		});
	},

	doCopy: function(o_options, o_values, o_store, f_callback) {

		var o_json = Portfolio.registry.util.Service.getJsonData(o_options, "copy", o_values, o_store);

		Ext.Ajax.request({
			url: Portfolio.registry.util.Service.getPath(),
			jsonData: o_json,
			success: function (i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				if (!o_result.success) {

					ip2.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: Portfolio.registry.util.Service.getMessage(o_result),
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						}),
						yesFn: function() {
							f_callback(false);
						}
					});
				}
				else {
					f_callback(true);
				}
			},
			failure: function(i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				ip2.messageBox({
					icon: Ext.MessageBox.ERROR,
					title: ip2.i18n({
						da: "Fejl",
						en: "Error"
					}),
					closable: true,
					message: Portfolio.registry.util.Service.getMessage(o_result),
					yesText: ip2.i18n({
						da: "OK",
						en: "OK"
					}),
					yesFn: function() {
						f_callback(false);
					}
				});
			}
		});
	},

	doMove: function(o_options, o_values, o_store, f_callback) {

		var o_json = Portfolio.registry.util.Service.getJsonData(o_options, "move", o_values, o_store);

		Ext.Ajax.request({
			url: Portfolio.registry.util.Service.getPath(),
			jsonData: o_json,
			success: function (i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				if (!o_result.success) {

					ip2.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: Portfolio.registry.util.Service.getMessage(o_result),
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						}),
						yesFn: function() {
							f_callback(false);
						}
					});
				}
				else {
					f_callback(true);
				}
			},
			failure: function(i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				ip2.messageBox({
					icon: Ext.MessageBox.ERROR,
					title: ip2.i18n({
						da: "Fejl",
						en: "Error"
					}),
					closable: true,
					message: Portfolio.registry.util.Service.getMessage(o_result),
					yesText: ip2.i18n({
						da: "OK",
						en: "OK"
					}),
					yesFn: function() {
						f_callback(false);
					}
				});
			}
		});
	},

	setValue: function(o_options, o_value, o_store, f_callback) {

		var o_record = o_value;
		var s_methode = "set";

		if (o_store) {
			s_methode = "setDataStore";
		}

		var o_json = Portfolio.registry.util.Service.getJsonData(o_options, s_methode, o_record, o_store);

		Ext.Ajax.request({
			url: Portfolio.registry.util.Service.getPath(),
			jsonData: o_json,
			success: function (i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				if (!o_result.success) {

					ip2.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: Portfolio.registry.util.Service.getMessage(o_result),
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						})
					});
				}
				else {
					f_callback(o_record);
				}
			},
			failure: function(i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				ip2.messageBox({
					icon: Ext.MessageBox.ERROR,
					title: ip2.i18n({
						da: "Fejl",
						en: "Error"
					}),
					closable: true,
					message: Portfolio.registry.util.Service.getMessage(o_result),
					yesText: ip2.i18n({
						da: "OK",
						en: "OK"
					})
				});
			}
		});
	},

	setSingleValue: function(o_options, s_key, value, o_store, f_callback) {

		var s_methode = "single";
		if (o_store) {
			s_methode = "setDataStore";
		}

		var o_json = Portfolio.registry.util.Service.getJsonData(o_options, s_methode, {
			key: s_key,
			value: value
		}, o_store);

		Ext.Ajax.request({
			url: Portfolio.registry.util.Service.getPath(),
			jsonData: o_json,
			success: function (i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				if (!o_result.success) {

					ip2.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: Portfolio.registry.util.Service.getMessage(o_result),
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						})
					});
					f_callback();
				}
				else {
					f_callback();
				}
			},
			failure: function(i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				ip2.messageBox({
					icon: Ext.MessageBox.ERROR,
					title: ip2.i18n({
						da: "Fejl",
						en: "Error"
					}),
					closable: true,
					message: Portfolio.registry.util.Service.getMessage(o_result),
					yesText: ip2.i18n({
						da: "OK",
						en: "OK"
					})
				});
			}
		});
	},

	deleteEntry: function(o_options, o_record, o_store, f_callback) {

		var o_json = Portfolio.registry.util.Service.getJsonData(o_options, "delete", o_record, o_store);

		Ext.Ajax.request({
			url: Portfolio.registry.util.Service.getPath(),
			jsonData: o_json,
			success: function (i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				if (!o_result.success) {

					ip2.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: Portfolio.registry.util.Service.getMessage(o_result),
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						})
					});
				}
				else {
					f_callback();
				}
			},
			failure: function(i_response, request) {

				var o_result = Ext.decode(i_response.responseText, true) || {};

				ip2.messageBox({
					icon: Ext.MessageBox.ERROR,
					title: ip2.i18n({
						da: "Fejl",
						en: "Error"
					}),
					closable: true,
					message: Portfolio.registry.util.Service.getMessage(o_result),
					yesText: ip2.i18n({
						da: "OK",
						en: "OK"
					})
				});
			}
		});
	},

	getMessage: function(o_values) {

		var i_self = this;

		var i_template = i_self.getErrorTpl();

		return i_template.apply(o_values);
	},

	createErrorTemplate: function() {

		var i_template = Ext.create("Ext.XTemplate",
			"<div>",
				"<h4>" + ip2.i18n({
					da: "Beskrivelse",
					en: "Description"
				}) + "</h2>",
				"<span>{description}</span>",
				"<h4>" + ip2.i18n({
					da: "Besked",
					en: "Message"
				}) + "</h2>",
				"<span>{message}</span>",
				"<span>{msg}</span>",
			"</div>"
		);

		i_template.compile();

		return i_template;
	}
});
