//================================================================================================================
// Objetivos - Fazer a conexÃ£o com o Datasul WSEXECBO
//
// ParÃ¢metros:
//  - usuario - opcional
//  - programName   - obrigatorio
//  - procedureName - obrigatÃ³rio
//  - json          - obrigatÃ³rio
//
// Retorno:
//  - retorna uma coluna sendo a resposta do ExecBO conforme a chamada realizada
//
// 001 - Denilson Silva - 21/01/2019 - Passa a ter uma alternativa de usuÃ¡rio para obter o token, basta passar o parametro usuario
// 002 - Denilson Silva - 28/01/2019 - Passa a retornar, alÃ©m da coluna "response" a coluna msgErro para mostrar a mensagem de erro
//=================================================================================================================================

function createDataset(fields, constraints, sortFields) {
	
	log.info("=== DatasulCall: conectando o servico EXECBO para: " + getValue('WKUser'));
	
	// Utiliza o ServiceManager para obter uma referencia ao servico.
	var serviceProvider = ServiceManager.getService('WSEXECBO');
	var serviceLocator  = serviceProvider.instantiate('com.totvs.framework.ws.execbo.service.WebServiceExecBO');
	var service = serviceLocator.getWebServiceExecBOPort();
      
	var newDataset = DatasetBuilder.newDataset();
	newDataset.addColumn("response");
      
	var dataRow = new Array();
      
	var programName 	= new String(constraintInitialValue(constraints, "programName"));
	var procedureName 	= new String(constraintInitialValue(constraints, "procedureName"));
	var jsonParams 		= new String(constraintInitialValue(constraints, "json"));
	
	//var usuario 		= new String(constraintInitialValue(constraints, "usuario"));
  	var usuario = '<USUARIO_EXECBO_PADRAO>';
  	for (var i=0; i<constraints.length; i++) {
		//log.info(constraints[i].fieldName + " " + constraints[i].initialValue);
		if (constraints[i].fieldName == "usuario") { usuario = constraints[i].initialValue;	}
	}	

	//log.info("==== programName: " + programName);
	//log.info("==== procedureName: " + procedureName);
	//log.info("==== jsonParams: " + jsonParams);
	
	try {
		
		log.info("=== DatasulCall: buscando token para " + usuario);
		var token = service.userLogin(usuario);
		// Chama a procedure passando os parametros e o token de autenticacao.
		log.info("=== DatasulCall: quem chamou.: " + getValue('WKUser'));
		log.info("=== DatasulCall: programa....: " + programName);
		log.info("=== DatasulCall: procedure...: " + procedureName);
		log.info("=== DatasulCall: procedure Token...: " + token);
	    log.info("=== DatasulCall: procedure jSon...: " + jsonParams);
		var resp = service.callProcedureWithToken(token, programName, procedureName, jsonParams);
		// Converte o resultado para um objeto
		//var respObj = JSON.parse(resp);
		//log.info("======== datasulcall: " + resp);
		dataRow[0] = resp;
      
		// Cria os registros
		newDataset.addRow(dataRow);			
		
	} catch (e) {
		log.info("=== DatasulCall: erro (e): " + e);
		log.info("=== DatasulCall: erro (e.message): " + e.message);
		desc_erro = e.message;

		//Verifica se o retorno de erro Ã© do ExecBO porque o retorno inicia com "com.totvs.framework.ws.execbo.service.ExecBOServiceException: <mensagem>...."
		// Exemplo: JavaException: javax.xml.ws.soap.SOAPFaultException: com.totvs.framework.ws.execbo.service.ExecBOServiceException: ERROR condition: ** "ecm/fluig_utb.r" was not found. (293) (7211)
		if (desc_erro.indexOf('ExecBOServiceException')) {
			desc_erro  = desc_erro.split('ExecBOServiceException:')[1];
			if(desc_erro.indexOf('ERROR condition:')) {
				desc_erro  = desc_erro.split('ERROR condition:')[1];
			}
		}
		
		newDataset.addColumn("msgErro");
		newDataset.addRow(new Array('ERRO',desc_erro));		
	}
  
	log.info("=== DatasulCall: fim");
	
	return newDataset;
 
	//} catch (e) {
	//	var errDataset = DatasetBuilder.newDataset();
	//	errDataset.addColumn("Erro");
	//	errDataset.addRow(new Array("ERRO"));
	//	return errDataset;
	//}
}

function constraintInitialValue(constraints, campo) {
    for (var cons = 0; cons < constraints.length; cons++) {
        var constraint = constraints[cons];
        
        if (constraint.getFieldName().equals(campo)) {
            return constraint.getInitialValue();
        }
    }
    
    return "";
}

