/**
 * Dataset: ds_execbo_datasul
 * Tipo: ServiceManager (WebService SOAP)
 * Descricao: Dataset generico para chamar qualquer procedure Datasul via ExecBO.
 *            Recebe programName, procedureName e json via constraints.
 *
 * Constraints OBRIGATORIAS:
 *   - programName: nome do programa Datasul (ex: "prg/btb/btb962za.p")
 *   - procedureName: nome da procedure (ex: "piBuscaCliente")
 *   - json: JSON de entrada para a procedure
 *
 * Exemplo de chamada:
 *   var c1 = DatasetFactory.createConstraint("programName", "prg/btb/btb962za.p", "prg/btb/btb962za.p", ConstraintType.MUST);
 *   var c2 = DatasetFactory.createConstraint("procedureName", "piBuscaCliente", "piBuscaCliente", ConstraintType.MUST);
 *   var c3 = DatasetFactory.createConstraint("json", '{"codCliente":"00001"}', '{"codCliente":"00001"}', ConstraintType.MUST);
 *   var ds = DatasetFactory.getDataset("ds_execbo_datasul", null, new Array(c1, c2, c3), null);
 *
 * Retorno:
 *   Coluna "response" com o JSON de retorno do Datasul
 *   Coluna "msgErro" em caso de erro
 */
function createDataset(fields, constraints, sortFields) {
    var dataset = DatasetBuilder.newDataset();
    dataset.addColumn("response");

    // Ler parametros das constraints
    var programName = constraintValue(constraints, "programName");
    var procedureName = constraintValue(constraints, "procedureName");
    var jsonParams = constraintValue(constraints, "json");

    // Validar parametros obrigatorios
    if (programName == "" || procedureName == "") {
        dataset.addColumn("msgErro");
        dataset.addRow(new Array("", "Parametros programName e procedureName sao obrigatorios."));
        return dataset;
    }

    log.info("ds_execbo_datasul - Chamando: " + programName + " / " + procedureName);

    try {
        // Buscar servico cadastrado no Painel do Fluig
        var serviceProvider = ServiceManager.getService("WSEXECBO");
        var serviceLocator = serviceProvider.instantiate(
            "com.totvs.framework.ws.execbo.service.WebServiceExecBO");
        var service = serviceLocator.getWebServiceExecBOPort();

        // Autenticar
        var token = service.userLogin("fluig-integr");

        // Chamar procedure
        var resp = service.callProcedureWithToken(
            token, programName, procedureName, jsonParams);

        log.info("ds_execbo_datasul - Resposta recebida (tamanho: " + resp.length() + ")");
        dataset.addRow(new Array(resp));

    } catch (e) {
        log.error("ds_execbo_datasul ERRO: " + e.message);
        dataset.addColumn("msgErro");
        dataset.addRow(new Array("ERRO", e.message));
    }

    return dataset;
}

/**
 * Helper: extrai valor de uma constraint pelo fieldName
 */
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 "";
}
