/*
 * Funciones para SOAP
 */

define([
    "dijit/registry",
	"dojo/request",
	"dojo/_base/lang",
	"dojox/xml/parser",
	"dojo/query",
	"handsoft/utils",
	"handsoft/message_dialog"], function(registry, request, lang, parser, query, utils, message_dialog){	
	var options = {
		url: "",
		ns: "",
		port: ""
	};
 
	return {
		setOptions: function(newSettings){
			lang.mixin(options, newSettings);
		},
		
		call: function(method, params, callback, error_callback){
			
			if (!ibus_isOnline()){
				message_dialog.show("No hay conexi&oacute;n de red");
				return;
			}
			
			var soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"+
				"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\""+options.ns+"/\">\r\n"+
				"   <soapenv:Header/>\r\n"+
				"   <soapenv:Body>\r\n"+
				"      <tem:"+method+">\r\n";
			
			if (params !== null)
			{
				for(var key in params){
					var attrName = key;
					var attrValue = params[key];
					
					soapMessage += "         <tem:"+attrName+">"+attrValue+"</tem:"+attrName+">\r\n";
				}
			}
				
			soapMessage +=	"      </tem:"+method+">\r\n"+
				"   </soapenv:Body>\r\n"+
				"</soapenv:Envelope>";

			
			registry.byId("dlg_loading").show();
			request.post(options.url, {
				data: soapMessage,
				timeout: 60000,/*30 seg */
				headers: {
					"Content-Type": "text/xml; charset=\"utf-8\"",
					"SOAPAction": options.ns + "/"+options.port+"/"+method
				}

			}).then(function(response){
				
				var result = parser.parse(response);
				var docNode = result.documentElement;
				var r = query(method + "Result", docNode);
				
				registry.byId("dlg_loading").hide();
				
				if (r.length > 0){
					var result_string = r[0].textContent;					
					
					/* Verifico respuesta */
					if ((result_string.textContent === null) || (result_string.textContent == '')){
						error_callback("-2", null);
						
						return;
					}

					// Extraigo el codigo de error
					var error_string = result_string.toLowerCase();

					if (error_string.indexOf("error:") == 0){
						var error_code = error_string[6];
						
						/* Error es 0, osea no es error :S */
						if (error_code == "0"){
							callback(result_string);
							return;
						} else if ((error_code == "2") && (error_string.length > 8)){
							/* Verifico si traigo algun mensaje de error */
							var message = result_string.substring(8);
							
							error_callback(error_code, message);
							return;
						}
						error_callback(error_code, null);
						
						return;
					}
					
					callback(result_string);
					return;
				}
				
				error_callback("-3", null);
				
			}, function(error){
				registry.byId("dlg_loading").hide();
				error_callback("-1", null);
			});
		}
	};
});
