/**
 * TEMPLATE: dataset-servicemanager-base.js
 * =============================================
 * Dataset que chama WebService via ServiceManager.
 * O servico deve estar cadastrado no Painel do Fluig.
 *
 * PADRAO DE PRODUCAO (VIPal ExecBO, Soprano):
 * 1. Obter servico via ServiceManager.getService()
 * 2. Instanciar o locator e obter a porta
 * 3. Fazer login (token) se necessario
 * 4. Chamar a procedure/metodo
 * 5. Retornar resposta como dataset
 */

function createDataset(fields, constraints, sortFields) {

    var dataset = DatasetBuilder.newDataset();
    dataset.addColumn("response");

    // =============================================
    // LER PARAMETROS VIA CONSTRAINTS
    // =============================================
    var programName = constraintValue(constraints, "programName");
    var procedureName = constraintValue(constraints, "procedureName");
    var jsonParams = constraintValue(constraints, "json");
    var usuario = constraintValue(constraints, "usuario");

    if (usuario == "") {
        usuario = "${USUARIO_PADRAO}";
    }

    log.info("=== ${NOME_DATASET}: programa: " + programName);
    log.info("=== ${NOME_DATASET}: procedure: " + procedureName);

    try {
        // =============================================
        // OBTER SERVICO DO PAINEL
        // =============================================
        var serviceProvider = ServiceManager.getService("${NOME_SERVICO}");
        var serviceLocator = serviceProvider.instantiate("${CLASSE_SERVICO}");
        var service = serviceLocator.${METODO_PORTA}();

        // =============================================
        // AUTENTICACAO (se necessario)
        // =============================================
        var token = service.userLogin(usuario);
        log.info("=== ${NOME_DATASET}: token obtido");

        // =============================================
        // CHAMAR PROCEDURE
        // =============================================
        var resp = service.callProcedureWithToken(
            token, programName, procedureName, jsonParams);

        log.info("=== ${NOME_DATASET}: resposta recebida");
        dataset.addRow(new Array(resp));

    } catch (e) {
        log.error("=== ${NOME_DATASET} ERRO: " + e.message);

        // Tratar erro especifico do ExecBO
        var descErro = e.message;
        if (descErro.indexOf("ExecBOServiceException") >= 0) {
            descErro = descErro.split("ExecBOServiceException:")[1];
            if (descErro.indexOf("ERROR condition:") >= 0) {
                descErro = descErro.split("ERROR condition:")[1];
            }
        }

        dataset.addColumn("msgErro");
        dataset.addRow(new Array("ERRO", descErro));
    }

    log.info("=== ${NOME_DATASET}: fim");
    return dataset;
}

/**
 * Le o valor de uma constraint pelo nome do campo.
 */
function constraintValue(constraints, campo) {
    if (constraints == null) return "";
    for (var i = 0; i < constraints.length; i++) {
        if (constraints[i].getFieldName().equals(campo)) {
            return constraints[i].getInitialValue();
        }
    }
    return "";
}
