package com.linx;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.util.Base64;
import android.os.Bundle;

import com.linx.dposandroid.CDPOSDRVTELA;
import com.linx.dposandroid.CPOS;
import com.linx.DTEFMobile;
import com.linx.dtefmobile.*;
import org.json.JSONObject;

import rede.smartrede.sdk.FlexTipoPagamento;
import rede.smartrede.sdk.Intents;
import rede.smartrede.sdk.Payment;
import rede.smartrede.sdk.PaymentStatus;
import rede.smartrede.sdk.Receipt;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DTEFMobile extends CordovaPlugin implements CDTEFMobilePromptX {
  public static String TAG = "DTEFMobile";
  
  private CallbackContext callbackContext;
  private CallbackContext PUBLIC_CALLBACKS = null;
  private JSONObject params;
  private CDTEFMobile oDTEFMobile;
  private CDTEFMobilePromptX promptX;
  //Activity promptX;
  private boolean bRespostaRecebida;
  private CRetorno oRetornoRespostaRecebida;
  private String resposta;

  private static final String DTEF_MOBILE_VERSION = "1.3.19.1";
  private static final int PAGAMENTO_REDE_REQUEST     = 500;
  private static final int REPRINT_REDE_REQUEST       = 510;
  private static final int CANCELAMENTO_REDE_REQUEST  = 520;
  
  public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);
    // your init code here    
    Log.v("DTEFMobile", "initialize"); 
  }
  
  public void setActivityResultCallback(CordovaPlugin plugin) {
    //this.activityResultCallback = plugin;
    Log.v("DTEFMobile", "setActivityResultCallback"); 
  }
  
  public Bundle onSaveInstanceState() {
    Log.v("DTEFMobile", "onSaveInstanceState()"); 
    Bundle state = new Bundle();
    return state;
  }

  public void onRestoreStateForActivityResult(Bundle state, CallbackContext callbackContext) {
    Log.v("DTEFMobile", "onRestoreStateForActivityResult callbackContext = " + callbackContext);
    this.callbackContext = callbackContext;
    
    PUBLIC_CALLBACKS = callbackContext;
  }  
  
  public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    this.params = args.getJSONObject(0);
    String parameters = "";
    Log.v("DTEFMobile", "DTEFMobile versao " + DTEF_MOBILE_VERSION + " action = " + action);
    Log.v("DTEFMobile", "DTEFMobile callbackContext = " + callbackContext);
    
    if (action.equals("executeTransaction") ||
        action.equals("confirmTransaction") ||
        action.equals("undoTransaction") ||
        action.equals("finalizeTransaction"))
    {
      if (this.params.has("parameters")) {
        parameters = params.getString("parameters");
      }
      
      boolean bTelasPersonalizadas = false;
      String telasPersonalizadas = ValorParametro(parameters, "TipoInterface");
      if (telasPersonalizadas.equals("1"))
      bTelasPersonalizadas = true;
      
      int iCodigoTransacao = 0;
      String codigoTransacao = ValorParametro(parameters, "CodigoTransacao");
      if ((codigoTransacao != null) && !codigoTransacao.equals(""))
        iCodigoTransacao = Integer.parseInt(codigoTransacao);
      if (action.equals("confirmTransaction"))
        iCodigoTransacao = -2;
      else if (action.equals("undoTransaction"))
        iCodigoTransacao = -3;
      else if (action.equals("finalizeTransaction"))
        iCodigoTransacao = -4;
      
      PUBLIC_CALLBACKS = callbackContext;
      this.callbackContext = callbackContext;
      
      if (bTelasPersonalizadas)
      {
        if (this.params.has("parameters")) {
          parameters = params.getString("parameters");
        }
        Log.v("DTEFMobile", "executaTransacao antes parameters=" + parameters); 
        
        executaTransacao(callbackContext, iCodigoTransacao, parameters);
        Log.v("DTEFMobile", "executaTransacao depois"); 
      }
      else
      {
        Intent intent = new Intent(cordova.getActivity(), CDPOSDRVTELA.class);
        if (this.params.has("parameters")) {
          parameters = params.getString("parameters");
        }
        
        Log.v("DTEFMobile", "action = " + action + " parameters = " + parameters);
        
        intent.putExtra("parameters", parameters);
        intent.putExtra("action", action);
        if (this.cordova != null) {
          this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0);
        }
      }
    }
    else if (action.equals("executeTransactionSpecial"))
    {
      if (this.params.has("parameters")) {
        parameters = params.getString("parameters");
      }
      
      boolean bTelasPersonalizadas = false;
      String telasPersonalizadas = ValorParametro(parameters, "TipoInterface");
      if (telasPersonalizadas.equals("1"))
      bTelasPersonalizadas = true;
      
      int iCodigoTransacao = 0;
      String codigoTransacao = ValorParametro(parameters, "CodigoTransacao");
      if ((codigoTransacao != null) && !codigoTransacao.equals(""))
      iCodigoTransacao = Integer.parseInt(codigoTransacao);
      
      Log.v("DTEFMobile", "executeTransactionSpecial antes telas personalizadas=" + parameters); 
      
      this.callbackContext = callbackContext;
      if (bTelasPersonalizadas)
      {
        if (this.params.has("parameters")) {
          parameters = params.getString("parameters");
        }
        Log.v("DTEFMobile", "executaTransacaoEspecial antes parameters=" + parameters); 
        
        executaTransacaoEspecial(callbackContext, iCodigoTransacao, parameters);
        Log.v("DTEFMobile", "executaTransacaoEspecial depois"); 
      }
      else
      {
        Intent intent = new Intent(cordova.getActivity(), CDPOSDRVTELA.class);
        if (this.params.has("parameters")) {
          parameters = params.getString("parameters");
        }
        
        Log.v("DTEFMobile", "action = " + action + " parameters = " + parameters);
        
        intent.putExtra("parameters", parameters);
        intent.putExtra("action", action);
        if (this.cordova != null) {
          this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0);
        }
      }
    }
    else if (action.equals("printPOS")) 
    {
      if (this.params.has("parameters")) {
        parameters = params.getString("parameters");
      }
      
      /*boolean bTelasPersonalizadas = false;
      String telasPersonalizadas = ValorParametro(parameters, "TipoInterface");
      if (telasPersonalizadas.equals("1"))
        bTelasPersonalizadas = true;
      
      Log.v("DTEFMobile", "printPOS antes telas personalizadas=" + parameters);*/
      
      this.callbackContext = callbackContext;
      //if (bTelasPersonalizadas)
      //{
        if (this.params.has("parameters")) {
          parameters = params.getString("parameters");
        }
        
        //Log.v("DTEFMobile", "printPOS antes parameters=" + parameters); 
        
        printPOS(callbackContext, parameters);
        Log.v("DTEFMobile", "printPOS depois"); 
      //}
      /*else
      {
        // TODO: verificar activy no caso de telas padroes do plugin
        Intent intent = new Intent(cordova.getActivity(), CDPOSDRVTELA.class);
        if (this.params.has("parameters")) {
          parameters = params.getString("parameters");
        }
        
        Log.v("DTEFMobile", "action = " + action + " parameters = " + parameters);
        
        intent.putExtra("parameters", parameters);
        intent.putExtra("action", action);
        if (this.cordova != null) {
          this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0);
        }
      }*/
    }    
    else if (action.equals("printBarcode")) 
    {
      if (this.params.has("parameters")) {
        parameters = params.getString("parameters");
      }
      
      this.callbackContext = callbackContext;
      
      if (this.params.has("parameters")) {
        parameters = params.getString("parameters");
      }
      
      Log.v("DTEFMobile", "printBarcode antes parameters=" + parameters); 
      
      printBarcode(callbackContext, parameters);
      Log.v("DTEFMobile", "printBarcode depois"); 
    }
    else if (action.equals("comandoPOS"))
    {
      Intent intent = new Intent(cordova.getActivity(), CPOS.class);
      if (this.params.has("parameters")) {
        parameters = params.getString("parameters");
      }
      
      Log.v("DTEFMobile", "action = " + action + " parameters = " + parameters);
      
      intent.putExtra("parameters", parameters);
      intent.putExtra("action", action);
      if (this.cordova != null) {
        this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0);
      }
    }
    else if (action.equals("continueTransaction"))
    {
      Log.v("DTEFMobile", "action = " + action);
    }
    
    else if (action.equals("sendCallbackResponse"))
    {
      if (this.params.has("parameters")) {
        parameters = params.getString("parameters");
      }
      
      Log.v("DTEFMobile", "action = " + action + "  setRespostaRecebida ");
      Log.v("DTEFMobile", "parameters = " + parameters);
      resposta = parameters;
      
      JSONObject json = new JSONObject(parameters);
      
      oRetornoRespostaRecebida = new CRetorno();
      int resultado;
      try
      {
        resultado = Integer.parseInt(json.getString("resultado"));
      } catch (Exception e) {
        resultado = 0;
      }
      int intRetorno;
      try
      {
        intRetorno = Integer.parseInt(json.getString("intRetorno"));
      } catch (Exception e) {
        intRetorno = 0;
      }
      String stringRetorno = json.getString("stringRetorno");
      oRetornoRespostaRecebida.setResultado(resultado);
      oRetornoRespostaRecebida.setIntRetorno(intRetorno);
      oRetornoRespostaRecebida.setStringRetorno(stringRetorno);
      setRespostaRecebida(true);
      oDTEFMobile.setRespostaRecebida(true);
    }
    
    return true;
  }
  
  public synchronized void setRespostaRecebida(boolean value) {
    System.out.println("setRespostaRecebida = " + value);
    bRespostaRecebida = value;
  }
  
	public JSONObject setCamposRetornoPoynt(Payment payment) {
    Log.v("DTEFMobile", "setCamposRetornoPoynt inicio");

		Receipt receipt = payment.getReceipt();

    Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (1)");

		Date dtAgora = new Date();
		SimpleDateFormat fmtData = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat fmt24h = new SimpleDateFormat("HHmmss");
		SimpleDateFormat fmt12h = new SimpleDateFormat("hhmmss");
		
    String sData = fmtData.format(dtAgora);
    String sHora = fmt24h.format(dtAgora);
		
		String sCodigoResposta = "";
		String sTipoOperacao = "";
		String sTipoFinanciamento = "0"; //AV

    Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (2)");
    
		if (payment.getPaymentType() == FlexTipoPagamento.DEBITO)
		{
			sTipoFinanciamento = "0"; //AV
			sTipoOperacao = "01";
		}
		if (payment.getPaymentType() == FlexTipoPagamento.VOUCHER)
		{
			sTipoFinanciamento = "0"; //AV
			sTipoOperacao = "03";
		}
		else if (payment.getPaymentType() == FlexTipoPagamento.CREDITO_A_VISTA)
		{
			sTipoFinanciamento = "0"; //AV
			sTipoOperacao = "02";
		}
		else if (payment.getPaymentType() == FlexTipoPagamento.CREDITO_PARCELADO_EMISSOR)
		{
			sTipoFinanciamento = "1"; //PC ADM
			sTipoOperacao = "02";
		}
		else if (payment.getPaymentType() == FlexTipoPagamento.CREDITO_PARCELADO)
		{
			sTipoFinanciamento = "2"; //PC Loja
			sTipoOperacao = "02";
		}
		
		if (payment.getStatus().name() == "AUTHORIZED")
			sCodigoResposta = "00";
		else
			sCodigoResposta = "99";

    Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (3)");

		String sCNPJLoja = receipt.getCNPJ();
		sCNPJLoja = sCNPJLoja.replace(".", "");
		sCNPJLoja = sCNPJLoja.replace("/", "");
		sCNPJLoja = sCNPJLoja.replace("-", "");

    Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (4)");
		
		double dValorParcela = receipt.getInstallmentValue();
		int iValorParcela = (int) dValorParcela * 100;
		String sValorParcela = String.valueOf(iValorParcela);

    Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (5)");

    try
    {
      JSONObject jsonobj = new JSONObject();
      jsonobj.put("action", "");
    
      jsonobj.put("CodigoResposta", sCodigoResposta);
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (6)");

      jsonobj.put("Comprovante", "");
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (7)");

      jsonobj.put("NSU", receipt.getNSU());
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (8)");

      jsonobj.put("NSURede",  "");
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (9)");

      jsonobj.put("CodigoRede",  "7"); // fixo: "Rede"
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (10)");

      jsonobj.put("CodigoBandeira", ""); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (11)");

      jsonobj.put("CodigoAutorizacao", receipt.getAUTO()); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (12)");

      jsonobj.put("IndiceCodigoRede", ""); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (13)");

      jsonobj.put("IndiceCodigoBandeira", ""); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (14)");

      jsonobj.put("NumeroCartao", "");
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (15)");

      jsonobj.put("TipoOperacao", sTipoOperacao);
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (16)");

      jsonobj.put("TipoFinanciamento", sTipoFinanciamento); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (17)");

      if (sTipoFinanciamento != "0")
      {
        Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (18)");
        jsonobj.put("NumeroParcelas", String.valueOf(receipt.getInstallments()));

        Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (18.2)");

        jsonobj.put("ValorParcela", sValorParcela);
        Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (18.3)");
      }
      else
      {
        Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (19)");
        jsonobj.put("NumeroParcelas", "00");
        
        jsonobj.put("ValorParcela", "000");
        Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (19.1)");
      }

      jsonobj.put("CodigoProdutoCielo", ""); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (20)");

      jsonobj.put("ComprovanteReduzido", ""); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (21)");

      jsonobj.put("ComprovanteCliente", ""); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (22)");

      jsonobj.put("ComprovanteEstabelecimento", ""); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (23)");

      jsonobj.put("DataFiscal", sData); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (24)");

      jsonobj.put("HoraFiscal", sHora); 
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (25)");

      jsonobj.put("CNPJRede", "01425787000104");  // fixo: "Rede"
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (26)");

      jsonobj.put("ValorDesconto", "");
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (27)");

      jsonobj.put("NomeBandeira", receipt.getIssueName());
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (28)");

      jsonobj.put("CNPJLoja", sCNPJLoja);
      Log.v("DTEFMobile", "setCamposRetornoPoynt Passo (29)");
      
      return (jsonobj);
    }
    catch (JSONException e)
    {
      Log.v("DTEFMobile", "setCamposRetornoPoynt jsonException");
    }
    
    Log.v("DTEFMobile", "setCamposRetornoPoynt fim");
    return null;
	}
  
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.v("DTEFMobile", "onActivityResult  resultCode = " + resultCode);
    
    if (resultCode == Activity.RESULT_OK) 
    {
      Log.v("DTEFMobile", "onActivityResult Activity.RESULT_OK");
      if (data != null)
      {
        if (requestCode == PAGAMENTO_REDE_REQUEST) 
        {
          Log.v("DTEFMobile", "onActivityResult requestCode == PAGAMENTO_REDE_REQUEST");
          
          Payment payment = data.getParcelableExtra(Intents.INTENT_EXTRAS_PAYMENT);
          if (payment.getStatus().equals(PaymentStatus.AUTHORIZED)) 
          {
            Log.v("DTEFMobile", "onActivityResult PaymentStatus.AUTHORIZED");
            
            JSONObject jsonobj = new JSONObject();
            jsonobj = setCamposRetornoPoynt(payment);
            
            if (jsonobj != null)
            {
              Log.v("DTEFMobile", "onActivityResult resposta = " + jsonobj.toString());
              Log.v("DTEFMobile", "PUBLIC_CALLBACKS  = " + PUBLIC_CALLBACKS);
              
              if (PUBLIC_CALLBACKS != null)
              {
                //PUBLIC_CALLBACKS.success(jsonobj);
                PluginResult result = new PluginResult(PluginResult.Status.OK, jsonobj);
                result.setKeepCallback(true);
                PUBLIC_CALLBACKS.sendPluginResult(result);
              }
            }
            else
            {
              try 
              {
                JSONObject res = new JSONObject();
                res.put("action", "");
                //PUBLIC_CALLBACKS.success(res);
                PluginResult result = new PluginResult(PluginResult.Status.OK, res);
                result.setKeepCallback(true);
                PUBLIC_CALLBACKS.sendPluginResult(result);
              } catch (Exception e) {
              }
            }
            
            Log.v("DTEFMobile", "onActivityResult Activity.RESULT_OK");
          }
          else {
            Log.v("DTEFMobile", "onActivityResult Pagamento nao autorizado");
            //PUBLIC_CALLBACKS.error("Pagamento nao autorizado");
            PluginResult result = new PluginResult(PluginResult.Status.ERROR, "Pagamento nao autorizado");
            result.setKeepCallback(true);
            PUBLIC_CALLBACKS.sendPluginResult(result);
          }
          
          Log.v("DTEFMobile", "onActivityResult return");
          return;
        }
        else if (requestCode == REPRINT_REDE_REQUEST) {
          Log.v("DTEFMobile", "onActivityResult requestCode == REPRINT_REDE_REQUEST");
          
          if (resultCode == Activity.RESULT_OK) {
            Log.v("DTEFMobile", "onActivityResult Reimpressao OK");
            //setResult(RESULT_OK, getIntent());
          } 
          else {
            Log.v("DTEFMobile", "onActivityResult Operacao Cancelada");
            //setResult(RESULT_CANCELED, getIntent());
          }
          
          try 
          {
            JSONObject res = new JSONObject();
            res.put("action", "");
            //PUBLIC_CALLBACKS.success(res);
            PluginResult result = new PluginResult(PluginResult.Status.OK, res);
            result.setKeepCallback(true);
            PUBLIC_CALLBACKS.sendPluginResult(result);
          } catch (Exception e) {
          }
          
          Log.v("DTEFMobile", "onActivityResult return");
          return;
        }
        else if (requestCode == CANCELAMENTO_REDE_REQUEST) {
          Log.v("DTEFMobile", "onActivityResult requestCode == CANCELAMENTO_REDE_REQUEST");
          
          Payment payment = data.getParcelableExtra(Intents.INTENT_EXTRAS_PAYMENT);
          Receipt receipt;
          
          if (payment.getStatus().equals(PaymentStatus.COMPLETED)) {
            Log.v("DTEFMobile", "onActivityResult Completed");
          } 
          else if (payment.getStatus().equals(PaymentStatus.AUTHORIZED)) {
            Log.v("DTEFMobile", "onActivityResult AUTHORIZED");
            //receipt = payment.getReceipt();
          }
          
          if (resultCode==Activity.RESULT_OK) {
            Log.v("DTEFMobile", "onActivityResult Cancelamento OK");
            //setResult(RESULT_OK, getIntent());
          } 
          else {
            Log.v("DTEFMobile", "onActivityResult Operacao Cancelada");
            //setResult(RESULT_CANCELED, getIntent());
          }
          
          try 
          {
            JSONObject res = new JSONObject();
            res.put("action", "");
            //this.PUBLIC_CALLBACKS.success(res);
            PluginResult result = new PluginResult(PluginResult.Status.OK, res);
            result.setKeepCallback(true);
            PUBLIC_CALLBACKS.sendPluginResult(result);
          } catch (Exception e) {
          }
          
          Log.v("DTEFMobile", "onActivityResult return");
          return;
        }
        
        JSONObject res;
        try 
        {
          Log.v("DTEFMobile", "onActivityResult Activity.RESULT_OK data !=  null 1");
          res = new JSONObject(data.getStringExtra("Parameters"));
          Log.v("DTEFMobile", "onActivityResult Activity.RESULT_OK data !=  null 2");
        }
        catch (Exception e)
        {
          Log.v("DTEFMobile", "onActivityResult Activity.RESULT_OK data !=  null 3");
          Log.v("DTEFMobile", "excecao = " + e + " parameters = " + data.getStringExtra("Parameters"));
          Log.v("DTEFMobile", "onActivityResult Activity.RESULT_OK data !=  null 4");
          res = new JSONObject();
          Log.v("DTEFMobile", "onActivityResult Activity.RESULT_OK data !=  null 5");
        }
        Log.v("DTEFMobile", "onActivityResult resposta = " + data.getStringExtra("Parameters"));
        //PUBLIC_CALLBACKS.success(res);
        PluginResult result = new PluginResult(PluginResult.Status.OK, res);
        result.setKeepCallback(true);
        PUBLIC_CALLBACKS.sendPluginResult(result);
        Log.v("DTEFMobile", "onActivityResult Activity.RESULT_OK data !=  null 6");
      }
      else
      {
        Log.v("DTEFMobile", "onActivityResult Activity.RESULT_OK data is null");
        //PUBLIC_CALLBACKS.success(new JSONObject());
        PluginResult result = new PluginResult(PluginResult.Status.OK, new JSONObject());
        result.setKeepCallback(true);
        PUBLIC_CALLBACKS.sendPluginResult(result);
      }
    } else if (resultCode == Activity.RESULT_CANCELED && data != null) {
      Log.v("DTEFMobile", "onActivityResult Activity.RESULT_CANCELED 1");
      String error = data.getStringExtra("ERRORMESSAGE");
      
      JSONObject res;
      try 
      {
        Log.v("DTEFMobile", "onActivityResult Activity.RESULT_CANCELED data !=  null 1");
        res = new JSONObject(data.getStringExtra("Parameters"));
        Log.v("DTEFMobile", "onActivityResult Activity.RESULT_CANCELED data !=  null 2");
      }
      catch (Exception e)
      {
        Log.v("DTEFMobile", "onActivityResult Activity.RESULT_CANCELED data !=  null 3");
        Log.v("DTEFMobile", "excecao = " + e + " parameters = " + data.getStringExtra("Parameters"));
        Log.v("DTEFMobile", "onActivityResult Activity.RESULT_CANCELED data !=  null 4");
        res = new JSONObject();
        Log.v("DTEFMobile", "onActivityResult Activity.RESULT_CANCELED data !=  null 5");
      }
      
      //PUBLIC_CALLBACKS.error(res);
      PluginResult result = new PluginResult(PluginResult.Status.ERROR, res);
      result.setKeepCallback(true);
      PUBLIC_CALLBACKS.sendPluginResult(result);
    } else {
      Log.v("DTEFMobile", "onActivityResult Erro generico");
      //PUBLIC_CALLBACKS.error("Erro generico");
      PluginResult result = new PluginResult(PluginResult.Status.ERROR, "Erro generico");
      result.setKeepCallback(true);
      PUBLIC_CALLBACKS.sendPluginResult(result);
    }
  }
  
  public String ValorParametro(String parameters, String parameter)
  {
    Log.v("DTEFMobile", "ValorParametro parameters="+parameters + " - parameter = " + parameter); 
    
    String[] pars = parameters.split(";");
    for (int i = 0; i < pars.length; i++)
    {
      
      String par = pars[i];
      
      Log.v("DTEFMobile", "ValorParametro par="+par); 
      
      String[] keyvalues = par.split("=");
      String key = keyvalues[0];
      String value = keyvalues[1];
      
      Log.v("DTEFMobile", "ValorParametro key="+key + " - value=" +value); 
      
      if (key.equals(parameter))
      return value;
    }
    
    return "";
  }
  
  
  public void DefineParametrosDTEFMobile(CDTEFMobile oDTEFMobile, String parameters)
  {
    String[] pars = parameters.split(";");
    for (int i = 0; i < pars.length; i++)
    {
      String par = pars[i];
      
      Log.v("DTEFMobile", "DefineParametrosDTEFMobile par="+par); 
      
      String[] keyvalues = par.split("=");
      //String key = keyvalues[0];
      //String value = keyvalues[1];
      
      //Log.v("DTEFMobile", "DefineParametrosDTEFMobile key="+key + " - value=" +value); 
      //oDTEFMobile.setParameter(key, value);     
      oDTEFMobile.setParameter(keyvalues[0], keyvalues[1]);
    }   
  }
  
  
  public void executaTransacao(final CallbackContext callbackContext, final int iCodigoTransacao, String parameters) {
    oDTEFMobile = new CDTEFMobile();
    
    oDTEFMobile.setContext(this.cordova.getActivity().getApplicationContext());
    oDTEFMobile.setActivity(this.cordova.getActivity());
    
    promptX = this;
    
    // bloqueia rotacao da tela durante a transacao
    //    oTransacaoActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    final String sParametros = parameters;
    Log.v("DTEFMobile", "executaTransacao 1 parametros="+sParametros + " codigoTransacao=" + iCodigoTransacao); 
    
    if (iCodigoTransacao == -1) {
      oDTEFMobile.resumeTransaction("");
      return;
    }
    
    cordova.getThreadPool().execute(new Runnable() {
      public void run() {
        oDTEFMobile.setParameter("NomeAplicacao", "DPOSAndroid");
        
        Log.v("DTEFMobile", "executaTransacao 2 iCodigoTransacao=" + iCodigoTransacao + " parametros="+sParametros); 
        
        if (!sParametros.equals(""))          
        {
          DefineParametrosDTEFMobile(oDTEFMobile, sParametros);
        }
        else
        {
          oDTEFMobile.setParameter("ValorTransacao", "0000");
          oDTEFMobile.setParameter("CupomFiscal", "00001");
          oDTEFMobile.setParameter("TipoServidorTEF", "0"); // D-TEF
        } 
        
        final String sTipoServidor = oDTEFMobile.getParameter("TipoServidorTEF");
        Log.v("DTEFMobile", "executaTransacao sTipoServidor=[" + sTipoServidor + "]");

        if (sTipoServidor != null && sTipoServidor.equals("3")) // Poynt
        {
          Log.v("DTEFMobile", "executaTransacao sTipoServidor=[" + sTipoServidor + "]");
          cordova.setActivityResultCallback((CordovaPlugin) promptX);
        }

        final int iResultado;
        if (iCodigoTransacao == -2)
        {
          // confirma
          Log.v("DTEFMobile", "confirmTransaction");
          int iNSU = Integer.parseInt(ValorParametro(sParametros, "NSUTransacao"));
          oDTEFMobile.setPromptX(promptX);
          Log.v("DTEFMobile", "confirmTransaction nsu=" + iNSU);
          iResultado = oDTEFMobile.confirmTransaction(iNSU);
        }
        else if (iCodigoTransacao == -3)
        {
          // desfaz
          Log.v("DTEFMobile", "undoTransaction");
          int iNSU = Integer.parseInt(ValorParametro(sParametros, "NSUTransacao"));
          oDTEFMobile.setPromptX(promptX);
          Log.v("DTEFMobile", "undoTransaction nsu=" + iNSU);
          iResultado = oDTEFMobile.undoTransaction(iNSU);
        }
        else if (iCodigoTransacao == -4)
        {
          // finaliza
          Log.v("DTEFMobile", "finalizeTransaction");
          oDTEFMobile.setPromptX(promptX);
          iResultado = oDTEFMobile.finalizeTransaction();                     
        }
        else
        {  
          Log.v("DTEFMobile", "executeTransactionX"); 
          iResultado = oDTEFMobile.executeTransactionX(iCodigoTransacao, promptX);
        }
        
        Log.v("DTEFMobile", "executaTransacao resultado = " + iResultado); 
        
        if (iResultado == 0)
        {
          try 
          {
            JSONObject res = new JSONObject();
            res.put("action", "");
            res.put("Comprovante", oDTEFMobile.getParameter("Comprovante"));
            res.put("NSU", oDTEFMobile.getParameter("NSU"));
            res.put("CodigoRede", oDTEFMobile.getParameter("CodigoRede"));
            res.put("CodigoBandeira", oDTEFMobile.getParameter("CodigoBandeira"));
            res.put("IndiceCodigoBandeira", oDTEFMobile.getParameter("IndiceCodigoBandeira"));
            res.put("IndiceCodigoRede", oDTEFMobile.getParameter("IndiceCodigoRede"));
            res.put("TipoOperacao", oDTEFMobile.getParameter("TipoOperacao"));
            res.put("ComprovanteCliente", oDTEFMobile.getParameter("ComprovanteCliente"));
            res.put("ComprovanteEstabelecimento", oDTEFMobile.getParameter("ComprovanteEstabelecimento"));
            res.put("ComprovanteReduzido", oDTEFMobile.getParameter("ComprovanteReduzido"));
            res.put("NSURede", oDTEFMobile.getParameter("NSURede"));
            res.put("CodigoResposta", oDTEFMobile.getParameter("CodigoResposta"));
            res.put("CodigoAutorizacao", oDTEFMobile.getParameter("CodigoAutorizacao"));
            res.put("NumeroParcelas", oDTEFMobile.getParameter("NumeroParcelas"));
            res.put("NomeBandeira", oDTEFMobile.getParameter("NomeBandeira"));
            res.put("NumeroCartao", oDTEFMobile.getParameter("NumeroCartao"));
            res.put("TipoFinanciamento", oDTEFMobile.getParameter("TipoFinanciamento"));
            res.put("DataFiscal", oDTEFMobile.getParameter("DataFiscal"));
            res.put("HoraFiscal", oDTEFMobile.getParameter("HoraFiscal"));
            res.put("CNPJRede", oDTEFMobile.getParameter("CNPJRede"));
            res.put("ValorDesconto", oDTEFMobile.getParameter("ValorDesconto"));
            res.put("ValorPago", oDTEFMobile.getParameter("ValorPago"));
            res.put("NUMPDV", oDTEFMobile.getParameter("NUMPDV"));
            res.put("NUMLOJA", oDTEFMobile.getParameter("NUMLOJA"));
            res.put("NUMESTAB", oDTEFMobile.getParameter("NUMESTAB"));
            res.put("NumeroPDV", oDTEFMobile.getParameter("NumeroPDV"));
            res.put("NumeroLoja", oDTEFMobile.getParameter("NumeroLoja"));
            res.put("NumeroEmpresa", oDTEFMobile.getParameter("NumeroEmpresa"));
            callbackContext.success(res);
          } catch (Exception e) {
            Log.v("DTEFMobile", "executaTransacao exception = " + e.getMessage()); 
          }
        }
        else if (iResultado == 1)
        {
          // necessario esta condicao para esperar retorno do modulo de pagamento da Rede no Poynt
          Log.v("DTEFMobile", "onActivityResult Activity (processando pagamento...)");
        }
        else  
        {
          Log.v("DTEFMobile", "onActivityResult Activity.RESULT_CANCELED 2 MensagemErro");
          Log.v("DTEFMobile", "onActivityResult Activity.RESULT_CANCELED 2 MensagemErro = " + oDTEFMobile.getParameter("MensagemErro"));
          try 
          {
            JSONObject res = new JSONObject();
            res.put("action", "");
            res.put("MensagemErro", oDTEFMobile.getParameter("MensagemErro"));
            callbackContext.error(res);
          } catch (Exception e) {
          }
        }
      }
    });
  }    
  
  public void executaTransacaoEspecial(final CallbackContext callbackContext, final int iCodigoTransacao, String parameters) {
    oDTEFMobile = new CDTEFMobile();
    
    oDTEFMobile.setContext(this.cordova.getActivity().getApplicationContext());
    oDTEFMobile.setActivity(this.cordova.getActivity());
    
    promptX = this;
    // bloqueia rotacao da tela durante a transacao
    //    oTransacaoActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    final String sParametros = parameters;
    Log.v("DTEFMobile", "executaTransacaoEspecial 1 parametros="+sParametros + " codigoTransacao=" + iCodigoTransacao); 
    
    if (iCodigoTransacao == -1) {
      oDTEFMobile.resumeTransaction("");
      return;
    }
    
    Thread thread = new Thread()
    {
      @Override
      public void run() {         
        
        Log.v("DTEFMobile", "executaTransacaoEspecial 2 iCodigoTransacao=" + iCodigoTransacao + " parametros="+sParametros); 
        
        if (!sParametros.equals(""))          
        {
          DefineParametrosDTEFMobile(oDTEFMobile, sParametros);
        }
        
        oDTEFMobile.setParameter("TransacaoEspecialDadosEntrada", "111101"); // coleta de CPF
        
        final int iResultado;
        Log.v("DTEFMobile", "executaTransacaoEspecial vai chamar oDTEFMobile.executeTransactionSpecial"); 
        iResultado = oDTEFMobile.executeTransactionSpecial(iCodigoTransacao, promptX);
        
        Log.v("DTEFMobile", "executaTransacaoEspecial resultado = " + iResultado); 
        
        if (iResultado == 0)
        {
          JSONObject res;
          try 
          {
            res = new JSONObject();
            res.put("action", "");
            res.put("TransacaoEspecialDadosSaida", oDTEFMobile.getParameter("TransacaoEspecialDadosSaida"));
            callbackContext.success(res);
          } catch (Exception e) {
          }
        }
        else  
        {
          Log.v("DTEFMobile", "onActivityResult Activity.RESULT_CANCELED 3");
          callbackContext.error(oDTEFMobile.getParameter("MensagemErro"));
        } 
        
      }
    };
    
    thread.start();
  }    
  
  public void printPOS(final CallbackContext callbackContext, String parameters) {
    oDTEFMobile = new CDTEFMobile();
    final Activity oActivity = this.cordova.getActivity();
    
    oDTEFMobile.setContext(this.cordova.getActivity().getApplicationContext());
    oDTEFMobile.setActivity(this.cordova.getActivity());

    promptX = this;
    
    // bloqueia rotacao da tela durante a transacao
    //    oTransacaoActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    final String sParametros = parameters;
    Log.v("DTEFMobile", "printPOS parametros=[" + sParametros + "]");

//	final CordovaInterface Ccordova = this.cordova;
//	cordova.getThreadPool().execute(new Runnable() {
//      public void run()
//      {
        if (!sParametros.equals(""))
        {
          DefineParametrosDTEFMobile(oDTEFMobile, sParametros);
        }
        
        String telasPersonalizadas = ValorParametro(sParametros, "TipoInterface");
        
        String sTipoDados = ValorParametro(sParametros, "tipoDados"); //oDTEFMobile.getParameter("tipoDados");
        if (sTipoDados.equals(""))
        {
          try 
          {
            JSONObject res = new JSONObject();
            res.put("action", "");
            res.put("MensagemErro", "Parametro tipoDados nao informado!");
            callbackContext.error(res);
          } catch (Exception e) {
          }
        }
        
        String sDados = ValorParametro(sParametros, "valorDados"); //oDTEFMobile.getParameter("printDados");
        if (!sTipoDados.equals("1") && sDados.equals("")) // se nao for line_feed, requer o campo de dados para enviar para a impressora
        {
          try 
          {
            JSONObject res = new JSONObject();
            res.put("action", "");
            res.put("MensagemErro", "Parametro valorDados nao informado!");
            callbackContext.error(res);
          } catch (Exception e) {
          }
        }

        final int iResultado;
        final int iTipoDados = Integer.parseInt(sTipoDados);
        byte[] btDados = sDados.getBytes();
        
        Log.v("DTEFMobile", "printPOS vai chamar oDTEFMobile.printPOS");

        iResultado = oDTEFMobile.printPOS(oActivity, iTipoDados, btDados);
        Log.v("DTEFMobile", "printPOS resultado = " + iResultado); 
    
        if (iResultado == 0)
        {
          JSONObject res;
          try 
          {
            res = new JSONObject();
            res.put("action", "");
            callbackContext.success(res);
          } 
          catch (Exception e) {
          }
        }
        else
        {
          callbackContext.error(oDTEFMobile.getParameter("MensagemErro"));
        } 
        
//      }
//    });
  }
  
  public void printBarcode(final CallbackContext callbackContext, String parameters) {
    oDTEFMobile = new CDTEFMobile();
    final Activity oActivity = this.cordova.getActivity();
    
    oDTEFMobile.setContext(this.cordova.getActivity().getApplicationContext());
    oDTEFMobile.setActivity(this.cordova.getActivity());

    promptX = this;
    
    // bloqueia rotacao da tela durante a transacao
    //    oTransacaoActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    final String sParametros = parameters;
    Log.v("DTEFMobile", "printBarcode parametros=[" + sParametros + "]");

	//final CordovaInterface Ccordova = this.cordova;
	//cordova.getThreadPool().execute(new Runnable() {
//      public void run()
//      {
        if (!sParametros.equals(""))
        {
          DefineParametrosDTEFMobile(oDTEFMobile, sParametros);
        }
        
        String telasPersonalizadas = ValorParametro(sParametros, "TipoInterface");
        
        String sTipoDados = ValorParametro(sParametros, "tipoDados");
        if (sTipoDados.equals(""))
        {
          try 
          {
            JSONObject res = new JSONObject();
            res.put("action", "");
            res.put("MensagemErro", "Parametro tipoDados nao informado!");
            callbackContext.error(res);
          } catch (Exception e) {
          }
        }
        
        String sDados = ValorParametro(sParametros, "valorDados");
        if (sDados.equals("")) // se nao informado o tipo de Barcode a imprimir
        {
          try 
          {
            JSONObject res = new JSONObject();
            res.put("action", "");
            res.put("MensagemErro", "Parametro valorDados nao informado!");
            callbackContext.error(res);
          } catch (Exception e) {
          }
        }

        final int iResultado;
        final int iTipoDados = Integer.parseInt(sTipoDados);
        byte[] btDados = sDados.getBytes();
        
        Log.v("DTEFMobile", "printBarcode vai chamar oDTEFMobile.printBarcode");

        iResultado = oDTEFMobile.printBarcode(oActivity, iTipoDados, btDados);
        Log.v("DTEFMobile", "printBarcode resultado = " + iResultado); 
    
        if (iResultado == 0)
        {
          JSONObject res;
          try 
          {
            res = new JSONObject();
            res.put("action", "");
            callbackContext.success(res);
          } 
          catch (Exception e) {
          }
        }
        else
        {
          callbackContext.error(oDTEFMobile.getParameter("MensagemErro"));
        } 
        
//      }
//    });
  }      
  
  public JSONObject criaJSONFuncao(String nomeFuncao)
  {
    System.out.println("DTEFMobile.java - " + nomeFuncao);
    JSONObject json = new JSONObject();
    try {
      json.put("action", "InputCallback");
      json.put("function", nomeFuncao);
    } catch (JSONException e) { 
    }
    return json;
  }
  
  public void sendResult(String nomeFuncao, JSONObject json)
  {
    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, json);
    pluginResult.setKeepCallback(true);
    setRespostaRecebida(false);
    this.callbackContext.sendPluginResult(pluginResult);
    System.out.println("sendResult: " + nomeFuncao);
  }
  
  public CRetorno aguardaRecebeResposta(String nomeFuncao)
  {
    System.out.println("aguardaRecebeResposta - " + nomeFuncao + " inicio bRespostaRecebida = " + bRespostaRecebida);
    while (!bRespostaRecebida)
    {
      try {
        //        System.out.println("aguardando resposta - " + nomeFuncao + " resposta recebida = " + bRespostaRecebida);
        Thread.sleep(20);
      } catch (Exception e) {
      }
    }
    
    CRetorno oRetorno = new CRetorno();
    oRetorno.setResultado(oRetornoRespostaRecebida.getResultado());
    oRetorno.setStringRetorno(oRetornoRespostaRecebida.getStringRetorno());
    oRetorno.setIntRetorno(oRetornoRespostaRecebida.getIntRetorno());
    
    System.out.println("aguardaRecebeResposta = resultado = " + oRetorno.getResultado());
    System.out.println("aguardaRecebeResposta = stringRetorno = " + oRetorno.getStringRetorno());
    System.out.println("aguardaRecebeResposta = intRetorno = " + oRetorno.getIntRetorno());
    
    return oRetorno;
  }
  
  public void beep() {
    String nomeFuncao = "beep";
    JSONObject json = criaJSONFuncao(nomeFuncao);
    sendResult(nomeFuncao, json);
    aguardaRecebeResposta(nomeFuncao);
  }
  
  public void limpaDisplayTerminal() {
    String nomeFuncao = "limpaDisplayTerminal";
    JSONObject json = criaJSONFuncao(nomeFuncao);
    sendResult(nomeFuncao, json);
    aguardaRecebeResposta(nomeFuncao);
  }
  
  public void displayTerminal(String mensagem) {
    String nomeFuncao = "displayTerminal";
    JSONObject json = criaJSONFuncao(nomeFuncao);
    try
    {
      json.put("mensagem", mensagem);
    } catch (JSONException e) { };
    sendResult(nomeFuncao, json);
    aguardaRecebeResposta(nomeFuncao);
  }
  
  public void displayErro(String mensagem) {
    String nomeFuncao = "displayErro";
    JSONObject json = criaJSONFuncao(nomeFuncao);
    try
    {
      json.put("mensagem", mensagem);
    } catch (JSONException e) { };
    sendResult(nomeFuncao, json);
    aguardaRecebeResposta(nomeFuncao);
  }
  
  public void mensagem(String mensagem) {
    String nomeFuncao = "mensagem";
    JSONObject json = criaJSONFuncao(nomeFuncao);
    try
    {
      json.put("mensagem", mensagem);
    } catch (JSONException e) { };
    sendResult(nomeFuncao, json);
    aguardaRecebeResposta(nomeFuncao);
  }
  
  public int solicitaConfirmacao(String mensagem) {
    String funcao = "solicitaConfirmacao";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("mensagem", mensagem);
    } catch (JSONException e) { };
    sendResult(funcao, json);
    CRetorno oRetorno = aguardaRecebeResposta(funcao);
    return oRetorno.getResultado();
  }
  
  public void mensagemAlerta(String mensagem) {
    String funcao = "mensagemAlerta";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("mensagem", mensagem);
    } catch (JSONException e) { };
    sendResult(funcao, json);
    aguardaRecebeResposta(funcao);
  }
  
  public CRetorno entraCartao(String label, String numeroCartao) {
    String funcao = "entraCartao";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("label", label);
      json.put("numeroCartao", numeroCartao);
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public CRetorno entraDataValidade(String label, String dataValidade) {
    String funcao = "entraDataValidade";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("label", label);
      json.put("dataValidade", dataValidade);
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public CRetorno entraData(String label, String data) {
    String funcao = "entraData";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("label", label);
      json.put("data", data);
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public CRetorno entraCodigoSeguranca(String label, String codigoSeguranca, int tamanhoMax) {
    String funcao = "entraCodigoSeguranca";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("label", label);
      json.put("codigoSeguranca", codigoSeguranca);
      json.put("tamanhoMax", Integer.toString(tamanhoMax));
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public CRetorno selecionaOpcao(String label, String opcoes, int opcao) {
    String funcao = "selecionaOpcao";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("label", label);
      json.put("opcoes", opcoes);
      json.put("opcao", Integer.toString(opcao));
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public CRetorno selecionaOpcaoEx(String label, String opcoes, int opcaoSelecionada, String identificador) {
    String funcao = "selecionaOpcaoEx";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("label", label);
      json.put("opcoes", opcoes);
      json.put("opcaoSelecionada", Integer.toString(opcaoSelecionada));
      json.put("identificador", identificador);
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public CRetorno entraValor(String label, String valor, String valorMinimo, String valorMaximo) {
    String funcao = "entraValor";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("label", label);
      json.put("valor", valor);
      json.put("valorMinimo", valorMinimo);
      json.put("valorMaximo", valorMaximo);
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public CRetorno entraNumero(String label, String numero, String numeroMinimo, String numeroMaximo, int iMinimoDigitos, int iMaximoDigitos, int iDigitosExatos) {
    String funcao = "entraNumero";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("label", label);
      json.put("numero", numero);
      json.put("numeroMinimo", numeroMinimo);
      json.put("numeroMaximo", numeroMaximo);
      json.put("minimoDigitos", iMinimoDigitos);
      json.put("maximoDigitos", iMaximoDigitos);
      json.put("digitosExatos", iDigitosExatos);
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public CRetorno entraString(String label, int limpaBuffer, String stringEntrada, int minimoDigitos, int maximoDigitos, int coletaSecreta) {
    String funcao = "entraString";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("label", label);
      json.put("limpaBuffer", Integer.toString(limpaBuffer));
      json.put("stringEntrada", stringEntrada);
      json.put("minimoDigitos", Integer.toString(minimoDigitos));
      json.put("maximoDigitos", Integer.toString(maximoDigitos));
      json.put("coletaSecreta", Integer.toString(coletaSecreta));
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public CRetorno entraMascara(boolean bLimpaTela, int colLabel, int linLabel, int linColeta, boolean limpaBuffer, String label, String mascara, String stringEntrada, boolean permiteEntra) {
    String funcao = "entraMascara";
    JSONObject json = criaJSONFuncao(funcao);
    try
    {
      json.put("bLimpaTela", Boolean.toString(bLimpaTela));
      json.put("colLabel", Integer.toString(colLabel));
      json.put("linLabel", Integer.toString(linLabel));
      json.put("linColeta", Integer.toString(linColeta));
      json.put("limpaBuffer", Boolean.toString(limpaBuffer));
      json.put("label", label);
      json.put("mascara", mascara);
      json.put("stringEntrada", stringEntrada);
      json.put("permiteEntra", Boolean.toString(permiteEntra));
    } catch (JSONException e) { };
    sendResult(funcao, json);
    return aguardaRecebeResposta(funcao);
  }
  
  public int operacaoCancelada() {
    String funcao = "operacaoCancelada";
    JSONObject json = criaJSONFuncao(funcao);
    sendResult(funcao, json);
    CRetorno oRetorno = aguardaRecebeResposta(funcao);
    return oRetorno.getResultado();
  }
  
  public int setaOperacaoCancelada(boolean cancelada) {
    String funcao = "setaOperacaoCancelada";
    JSONObject json = criaJSONFuncao(funcao);
    
    if (cancelada)
    {
      System.out.println("DTEFMobile setaOperacaoCancelada=true");
    }
    else
    {
      System.out.println("DTEFMobile setaOperacaoCancelada=false");
    }
    
    try
    {
      json.put("cancelada", Boolean.toString(cancelada));
    } catch (JSONException e) { };
    sendResult(funcao, json);
    CRetorno oRetorno = aguardaRecebeResposta(funcao);
    return oRetorno.getResultado();
  }
  
}				