package com.example.waoperations.Transference;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bimsdk.usb.UsbConnect;
import com.bimsdk.usb.io.OnDataReceive;

import com.example.waoperations.FontsOverride;
import com.example.waoperations.Shipping.ShippingAdapterTransfer;
import com.example.waoperations.Shipping.ShippingTransferDatabaseHelper2;
import com.example.waoperations.VoiceHelper;
import com.example.waoperations.R;
import com.example.waoperations.UserPermissionsDatabaseHelper;
import com.example.waoperations.Transference.WarehouseBarcodeDataBaseHelper;


import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.StrictMode;
import android.os.Vibrator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.speech.RecognizerIntent;
//import android.support.v4.view.MotionEventCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class TransferenceItemDetail extends Activity {  
private static final int REQUEST_CODE = 1234;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
public int COUNTER =0;
public String LASTPO,PONUMBER,EMP2,BOD,BODDEST;
final Context context = this;
public String ID, empresa,BodResult;
public String EXISTENTE,LOC,SKU,DATAAREAID,OFQTY,COUNTINGSTARTED,USERNAME,BARCODE,INVTID,LINENUM,CONFIG;
private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
public String Scanning="";
public String escaneo="";
public int execute=0;
public EditText ED;
public int timerstarted=0;
public Boolean timercompleted=false;
private TextView tvTexto;
private TransferenceDataBaseHelper2 databaseHelper;
private WarehouseBarcodeDataBaseHelper databaseHelper2;
private ShippingTransferDatabaseHelper2 databaseHelperShip;
private TransferenceDataBaseHelperPO databaseHelperPO;
private CrossDockingDataBaseHelper dataBaseHelperCrsDkc;
public String transferidf="";
public String itemidf="";
public String qtyremainf="";
public String qtyahorab="";
public String qtyahoraun="";
public String totalqty="";
public String inventtransidf="";
TransferenceAdapter1 newTransferenciasAdapter;
ShippingAdapterTransfer newShippingAdapterTransfer;
public int verificador=0;


@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
	setContentView(R.layout.watransferitem);
	
	databaseHelper = new TransferenceDataBaseHelper2(this.getApplicationContext());
	databaseHelperShip = new ShippingTransferDatabaseHelper2(this.getApplicationContext());
	databaseHelperPO = new TransferenceDataBaseHelperPO(this.getApplicationContext());
	//dataBaseHelperCrsDkc = new CrossDockingDataBaseHelper(this.getApplicationContext());
	
  ActionBar actionBar = getActionBar();
  actionBar.hide();

  actionBar.setSubtitle("Transfer AC");
  actionBar.setTitle("Warehouse");
  actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
  actionBar.setDisplayShowTitleEnabled(false); 
  actionBar.setDisplayShowTitleEnabled(true);
  actionBar.setDisplayHomeAsUpEnabled(false);
  actionBar.show(); 

	Intent intent = getIntent();
	this.PONUMBER = intent.getStringExtra("PO");
	this.EXISTENTE = intent.getStringExtra("EX");
	this.DATAAREAID = intent.getStringExtra("DATA");
	this.USERNAME = intent.getStringExtra("USER");
	this.EMP2= intent.getStringExtra("EMP2");
	this.BOD = intent.getStringExtra("BOD");
	this.INVTID=intent.getStringExtra("INVTID");
	this.BODDEST = intent.getStringExtra("BODDEST");
	this.LINENUM = intent.getStringExtra("LINENUM");
	this.CONFIG = intent.getStringExtra("CONFIG");

	
  EditText edittext = (EditText) this.findViewById(R.id.qtyamount);
  edittext.setText("");
  edittext.setClickable(false);
  edittext.setFocusable(false);
  ED = (EditText) this.findViewById(R.id.qtyamount);
  final TextView view = (TextView) findViewById(R.id.buscarheader);
	 	
	view.setOnClickListener(new View.OnClickListener() {
      //When you click the button, Alert dialog will be showed
      public void onClick(View v) {
      
      	AlertDialog.Builder alert = new AlertDialog.Builder(context);
      	alert.setTitle("Valide Item"); //Set Alert dialog title here
      	alert.setMessage("Digite Item:"); //Message here

          // Set an EditText view to get user input 
          final EditText input = new EditText(context);
          final AutoCompleteTextView text = new AutoCompleteTextView(context);
          
           final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
          
      	ArrayList<String> listItems=new ArrayList<String>();
          Cursor m = databaseHelper.getTransferenciasLines2(PONUMBER,LINENUM);
          
	            while(m.moveToNext())	
	            {
	            	listItems.add(m.getString(3));
	            }
          
	        ArrayAdapter adapter = new ArrayAdapter<String>(TransferenceItemDetail.this, android.R.layout.simple_list_item_activated_1, listItems);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

       	  text.setAdapter(adapter);
          alert.setView(text);
          input.selectAll();
      	  alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
      	public void onClick(DialogInterface dialog, int whichButton) {
    
      		String srt = text.getEditableText().toString().toUpperCase();
    	    Cursor cursor = databaseHelper.getTransferItem(PONUMBER,srt,INVTID);

	 	     if(cursor.getCount()>0){
	 	     cursor.moveToFirst();
	 	     ID= cursor.getString(0);
	 	     TextView qtyreceived = (TextView) findViewById(R.id.article);
	 	     TextView qty = (TextView) findViewById(R.id.ofqty);
	
				 qtyreceived.setText(cursor.getString(5));//6 QTYCOUNTED
				 String UnidDisp= cursor.getString(11);//15  RESERVPHYSICAL
	 	     if(UnidDisp.equals("null")){
	 	    	UnidDisp="0";
	 	     }
	 	     
	 	    try{
				Double Qt = Double.parseDouble(UnidDisp);
				NumberFormat nf = NumberFormat.getInstance();
				nf.setMaximumFractionDigits(0);// set as you need
				UnidDisp=nf.format(Qt).replace(",", "");
			}catch(Exception e){}
	 	    
		 	    if(UnidDisp.equals("1"))
		 	    {
		 	    		qty.setText("de "+UnidDisp+ " bulto "+CONFIG+ " disponible");
		 	    	
		 	    }else
		 	    {
		 	    	     qty.setText("de "+UnidDisp+ " bultos "+CONFIG+ " disponibles");
		 	    }
	 	     view.setText(cursor.getString(3));//ITEMID
	         view.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
	 	    	COUNTER++;
		        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
	
				Double cant = Double.parseDouble(cursor.getString(4));//5 QTYTRANSFER
		  		Double cantrec = Double.parseDouble(cursor.getString(5));//6 QTYCOUNTED
		  		Double remaining= cant-cantrec;
		  		NumberFormat nf = NumberFormat.getInstance();
	
		      nf.setMaximumFractionDigits(0);// set as you need
		      int remain2 = Double.valueOf(remaining).intValue();
		    	      
	  		  myEditText.setText(nf.format(remain2));
	          myEditText.setClickable(true);
	          //myEditText.setFocusable(true);
	          //myEditText.setFocusableInTouchMode(true);
	          //myEditText.requestFocus();
	          
	 		   SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 		   COUNTINGSTARTED = sd.format(new Date()); 
	 	 }else
 	     {
	 	    	view.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
	 	    	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	 	    	Toast.makeText(getBaseContext(), "No se pudo cargar Artículo. Intente nuevamente.", Toast.LENGTH_LONG).show();
	 	    	// Vibrate for 400 milliseconds
	 	    	v.vibrate(400);
		        COUNTER=0;
 	     }
	 	     imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
      	} // End of onClick(DialogInterface dialog, int whichButton)
      }); //End of alert.setPositiveButton
      	alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
      	  public void onClick(DialogInterface dialog, int whichButton) {
      	  // Canceled.
      	  dialog.cancel();
      	imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
      	  }
      }); //End of alert.setNegativeButton
      	AlertDialog alertDialog = alert.create();
      	alertDialog.show();
     /* Alert Dialog Code End*/        
   }// End of onClick(View v)
});

	if (!UsbConnect.isConnect(this)) 
	{
		UsbConnect.Connect(this);
	}
	
}


@Override
  public boolean onCreateOptionsMenu(Menu menu) 
{
      // Inflate the menu items for use in the action bar
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.calculatorandscan, menu);
      return super.onCreateOptionsMenu(menu);
  }

public boolean onOptionsItemSelected(MenuItem item) {
	  
  	int id = item.getItemId();
  	 if (id == R.id.refresh){
		 if(execute==0){

			 Intent i = new Intent();
			 i.setClassName("com.sec.android.app.popupcalculator","com.sec.android.app.popupcalculator.Calculator");
			 startActivity(i);

		 }else{
			 if(COUNTER==0){
				 TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
				 Cursor cursor = databaseHelper.getTransferItemBarcode(PONUMBER,Scanning);
				 if(cursor.getCount()>0){
					 cursor.moveToFirst();
					 ID= cursor.getString(0);
					 TextView qtyreceived = (TextView) findViewById(R.id.article);
					 TextView qty = (TextView) findViewById(R.id.ofqty);

					 qtyreceived.setText(cursor.getString(5));//6 QTYCOUNTED
					 String UnidDisp= cursor.getString(11);//15  RESERVPHYSICAL
					 if(UnidDisp.equals("null")){
						 UnidDisp="0";
					 }
					 
					 try{
							Double Qt = Double.parseDouble(UnidDisp);
							NumberFormat nf = NumberFormat.getInstance();
							nf.setMaximumFractionDigits(0);// set as you need
							UnidDisp=nf.format(Qt).replace(",", "");
						}catch(Exception e){}
					 
					 if(UnidDisp.equals("1"))
				 	    {
				 	    		qty.setText("de "+UnidDisp+ " bulto "+CONFIG+ " disponible");
				 	    }else
				 	    {
				 	    	     qty.setText("de "+UnidDisp+ " bultos "+CONFIG+ " disponibles");
				 	    }

					 buscarheader.setText(cursor.getString(3));//ITEMID
					 buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));

					 EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);

					 Double cant = Double.parseDouble(cursor.getString(4));//5
					 Double cantrec = Double.parseDouble(cursor.getString(5));//6
					 Double remaining= cant-cantrec;
					 NumberFormat nf = NumberFormat.getInstance();

					 nf.setMaximumFractionDigits(0);// set as you need
					 int remain2 = Double.valueOf(remaining).intValue();
					 
					 myEditText.setText(nf.format(remain2));
					 myEditText.setClickable(true);
					 //myEditText.setFocusable(true);
					 //myEditText.setFocusableInTouchMode(true);
					 //myEditText.requestFocus();
					 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					 COUNTINGSTARTED = sd.format(new Date());
					 COUNTER++;
				 }else{
					 buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
					 Toast.makeText(getBaseContext(), "No se pudo cargar Artículo. Intente nuevamente.", Toast.LENGTH_LONG).show();
					 Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
					 // Vibrate for 400 milliseconds
					 v.vibrate(400);
					 COUNTER=0;
				 }

				 Scanning="";
			 }
			 else if(COUNTER==1){

				 StrictMode.setThreadPolicy(policy);
				 TextView bodDestino = (TextView)findViewById(R.id.destino);
				 databaseHelper2 = new WarehouseBarcodeDataBaseHelper(context.getApplicationContext());
				 try{
					 String result = null;
					 InputStream is = null;

					 String v1 = "'"+Scanning+"'";
					 String v2 = "'"+EMP2+"'";
					 SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");

					 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					 nameValuePairs.add(new BasicNameValuePair("BARCODE",v1));
					 nameValuePairs.add(new BasicNameValuePair("EMPRESA",v2));

					 //apartir de aqui carga ruta
					 try
					 {
						 HttpClient httpclient = new DefaultHttpClient();
						 HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getWarehouseBarcode.php");
						 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
						 HttpResponse response = httpclient.execute(httppost);
						 HttpEntity entity = response.getEntity();
						 is = entity.getContent();
						 Log.e("log_tag", "connection success ");
						 //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
					 }
					 catch(Exception e)
					 {
						 Log.e("log_tag", "Error in http connection "+e.toString());
						 //        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
						 Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
					 }
					 //convert response to string
					 try{

						 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
						 StringBuilder sb = new StringBuilder();
						 String line = null;
						 while ((line = reader.readLine()) != null)
						 {
							 sb.append(line + "\n");
						 }
						 is.close();
						 result=sb.toString();
					 }
					 catch(Exception e)
					 {
						 Log.e("log_tag", "Error converting result "+e.toString());
					 }
					 int counter=0;
					 //parse json data
					 try{
						 databaseHelper2.deleteAllData();

						 JSONArray jArray = new JSONArray(result);
						 for(int i=0;i<jArray.length();i++)
						 {
							 try{
								 JSONObject no = jArray.getJSONObject(i);
								 String inventlocationid=no.getString("INVENTLOCATIONID");
								 String barcode=no.getString("BARCODE");
								 String dataareaid=no.getString("DATAAREAID");

								 NumberFormat nf = NumberFormat.getInstance();
								 nf.setMaximumFractionDigits(0);// set as you need

								 BodResult = inventlocationid;

								 databaseHelper2.saveWarehouseBarcode(inventlocationid.toUpperCase(),barcode,dataareaid);

								 counter++;

							 }catch(Exception e)
							 {
								 Log.e("log_tag", "Error cargando datos "+e.toString());
							 }
						 }
					 }
					 catch(JSONException e)
					 {
						 Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
					 } catch (IllegalArgumentException e) {
						 e.printStackTrace();
					 }
				 }catch(Exception e)
				 {
					 Log.e("log_tag", "Active el VPN para aplicar esta opción.");
				 }
				 EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
				 String dest = "";
				 TextView DES = (TextView)findViewById(R.id.destino);
				 Cursor x =databaseHelper2.getAllWarehouseBarcodeLines(escaneo);
				 if(x.getCount()>0 ){
					 if(BodResult.equals(BODDEST))
					 {
						 x.moveToFirst();
						 dest=x.getString(1);
						 DES.setText(dest);
						 myEditText.setFocusable(true);
						 myEditText.setFocusableInTouchMode(true);
						 myEditText.requestFocus();
						 DES.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
						 COUNTER=2;
					 }else
					 {
						 Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
						 // Vibrate for 400 milliseconds
						 v.vibrate(400);
						 bodDestino.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
						 Toast.makeText(getBaseContext(), "Bodega de destino incorrecta. Intente nuevamente.", Toast.LENGTH_LONG).show();
						 COUNTER=1;
					 }
				 }else{
						 Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
						 // Vibrate for 400 milliseconds
						 v.vibrate(400);
						 bodDestino.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
						 Toast.makeText(getBaseContext(), "No se pudo cargar bodega de destino. Intente nuevamente.", Toast.LENGTH_LONG).show();
						 COUNTER=1;
				 }
			 }
			 Scanning="";
		 }

	  } else if (id == R.id.add) 
	  {
			try{
                Intent intent = new Intent(
      	        "com.google.zxing.client.android.SCAN");
      	        //intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
      	        startActivityForResult(intent, 0);
        		 }catch(Exception e){ Toast.makeText(getApplicationContext(), "Debe instalar ZXING para utilizar esta opción.", Toast.LENGTH_SHORT).show();}	
	  }
	  
             return super.onOptionsItemSelected(item);
      }
  
  @SuppressWarnings("deprecation")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 if (requestCode == 0) {
			    if (resultCode == RESULT_OK) {
              
			     final String  contents = data.getStringExtra("SCAN_RESULT"); // This will contain your scan result
	             String format = data.getStringExtra("SCAN_RESULT_FORMAT");
	             TextView buscarheader = (TextView) this.findViewById(R.id.buscarheader);
	    	     Cursor cursor = databaseHelper.getTransferItemBarcode(PONUMBER,contents);
	    	     if(cursor.getCount()>0){
	    	     cursor.moveToFirst();
	    	     ID= cursor.getString(0);
	    	     TextView qtyreceived = (TextView) this.findViewById(R.id.article);
	    	     TextView qty = (TextView) this.findViewById(R.id.ofqty);
				 qtyreceived.setText(cursor.getString(5));//6 QTYCOUNTED
				 String UnidDisp= cursor.getString(11);//15  RESERVPHYSICAL
					 
	     	     if(UnidDisp.equals("null")){
	     	    	UnidDisp="0";
	     	     }
	     	     
	     	    try{
	    			Double Qt = Double.parseDouble(UnidDisp);
	    			NumberFormat nf = NumberFormat.getInstance();
	    			nf.setMaximumFractionDigits(0);// set as you need
	    			UnidDisp=nf.format(Qt).replace(",", "");
	    		}catch(Exception e){}
	     	    
	     	   if(UnidDisp.equals("1"))
	    	    {
	    	    		qty.setText("de "+UnidDisp+ " bulto "+CONFIG+ " disponible");
	    	    }else
	    	    {
	    	    	     qty.setText("de "+UnidDisp+ " bultos "+CONFIG+ " disponibles");
	    	    }
		       	 buscarheader.setText(cursor.getString(3));

	    	   	 buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
	    	   	 COUNTER++;
	    	       EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
                  myEditText.setClickable(true);
                  //myEditText.setFocusable(true);
                  myEditText.setFocusableInTouchMode(true);
                  //myEditText.requestFocus();
	    		    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    		    COUNTINGSTARTED = sd.format(new Date()); 	
	    	     }else{
	    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
	    	  	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	    	  	// Vibrate for 400 milliseconds
	    	  	v.vibrate(400);
	    	     COUNTER=0;
	    	     }}
	    	     else if(COUNTER==1){
					  
					  StrictMode.setThreadPolicy(policy); 
					  TextView bodDestino = (TextView)findViewById(R.id.destino);
	                	databaseHelper2 = new WarehouseBarcodeDataBaseHelper(context.getApplicationContext()); 
	                		try{
	                			String result = null;
	                	    	InputStream is = null;
	                	  
	                	    	String v1 = "'"+Scanning+"'";
	                			String v2 = "'"+EMP2+"'";
	                			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
	                		
	                	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	                	     	nameValuePairs.add(new BasicNameValuePair("BARCODE",v1));
	                	       	nameValuePairs.add(new BasicNameValuePair("EMPRESA",v2));

	                	//apartir de aqui carga ruta
	                		try
	                		{
	                	    	        HttpClient httpclient = new DefaultHttpClient();
	                	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getWarehouseBarcode.php");
	                	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	                	    	        HttpResponse response = httpclient.execute(httppost); 
	                	    	        HttpEntity entity = response.getEntity();
	                	    	        is = entity.getContent();
	                	    	        Log.e("log_tag", "connection success ");
	                	    	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
	                		}
	                	catch(Exception e)
	                		{
	                	    	        Log.e("log_tag", "Error in http connection "+e.toString());
	                	    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
	                	    	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
	                		}
	                	    	//convert response to string
	                		try{
	                			
	                	    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
	                	    	        StringBuilder sb = new StringBuilder();
	                	    	        String line = null;
	                	    	        while ((line = reader.readLine()) != null) 
	                	    	        {
	                	    	                sb.append(line + "\n");
	                	    	        }
	                	    	        is.close();
	                	    	        result=sb.toString();
	                		}
	                		catch(Exception e)
	                		{
	                	    	       Log.e("log_tag", "Error converting result "+e.toString());
	                		}
	                	int counter=0;
	                	    	//parse json data
	                	    	try{
	                	           databaseHelper2.deleteAllData();

	                	    	 	JSONArray jArray = new JSONArray(result);
	                	    		for(int i=0;i<jArray.length();i++)  
	                	            {
	                	    			try{
	                	    		   	JSONObject no = jArray.getJSONObject(i);
	                	    		    String inventlocationid=no.getString("INVENTLOCATIONID");
	                	    		    String barcode=no.getString("BARCODE");
	                	    		    String dataareaid=no.getString("DATAAREAID");
	                	    		   
	                		            NumberFormat nf = NumberFormat.getInstance();
	                		            nf.setMaximumFractionDigits(0);// set as you need
	                	               
	                	            	databaseHelper2.saveWarehouseBarcode(inventlocationid.toUpperCase(),barcode,dataareaid);

	                		            counter++;
	                		   
	                	    			}catch(Exception e)
	                		          	{ 
	                	    				 Log.e("log_tag", "Error cargando datos "+e.toString());
	                		          	}
	                		            }
	                	    	}
	                	    	catch(JSONException e)
	                	    	{
	                	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
	                	     	} catch (IllegalArgumentException e) {
	                				// TODO Auto-generated catch block
	                				e.printStackTrace();
	                			} 	
	                			}catch(Exception e)
	                	    	{
	                		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
	                		}
	                		
	                		String dest = "";
	                		TextView DES = (TextView)findViewById(R.id.destino); 
	                		Cursor x =databaseHelper2.getAllWarehouseBarcodeLines(escaneo);
	                		if(x.getCount()>0){
	                			x.moveToFirst();
	                			dest=x.getString(1);
	                			DES.setText(dest);
	                			DES.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
	                			//COUNTER=2;	    	    
	                		}else{
	                			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                          	// Vibrate for 400 milliseconds
	                          	v.vibrate(400);
	                          	bodDestino.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
		                	    Toast.makeText(getBaseContext(), "No se pudo cargar bodega de destino. Intente nuevamente.", Toast.LENGTH_LONG).show();	
	                		//COUNTER=1;
	                		}   
			    }
			    
		 }
  	}

	 public void onComplete(View view) {  
			
	         if(COUNTER==0){
				       	Toast.makeText(getApplicationContext(), "Verifique o digite artículo a enviar.", Toast.LENGTH_SHORT).show();
						Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
						intentemoslo.putExtra("voz","Verifique o digite artículo a enviar");
						startService(intentemoslo);	
						Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			       	// Vibrate for 400 milliseconds
						v.vibrate(400);
	         }
	         if(COUNTER==1){
			       		Toast.makeText(getApplicationContext(), "Verifique la bodega de destino para avanzar.", Toast.LENGTH_SHORT).show();	 
					  	Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
					  	intentemoslo.putExtra("voz","Verifique la bodega de destino para avanzar");  
					  	startService(intentemoslo);	
	     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                	// Vibrate for 400 milliseconds
	     				v.vibrate(400);    
	         }
	         
	         EditText edittext = (EditText) this.findViewById(R.id.qtyamount);
	         TextView qtyreceived = (TextView) this.findViewById(R.id.article);
	         if(COUNTER==2){
	        	 

	        Boolean TERMINUS=false;
	 		if(this.hasContent(edittext)==true){
	 		
	 			Cursor po = databaseHelper.getItemByID(ID);
				po.moveToFirst();
				int conteo=po.getCount();
	 		    NumberFormat nf = NumberFormat.getInstance();
	            nf.setMaximumFractionDigits(0);// set as you need
	            
	        Double qtycounted = Double.parseDouble(edittext.getText().toString().trim());
	 		Double qtyold = Double.parseDouble(qtyreceived.getText().toString().trim());
			Double totalreceived= qtycounted + qtyold;
			Double qtydisponible=Double.parseDouble(po.getString(11));//15
			Double qtysobrante = Double.parseDouble(po.getString(14));//13
			Double newQtyDisponible= qtydisponible - qtycounted;
			Double newQtysobrante= newQtyDisponible;
			

			if(newQtysobrante<0)
			{
				newQtysobrante=0.0;
			}else if(newQtyDisponible<0)
			{
				newQtyDisponible=0.0;
			}
			
	 		if(qtycounted>qtydisponible)
	 			{
	 			  	Toast.makeText(getApplicationContext(), "La cantidad a enviar no puede exceder el límite establecido.", Toast.LENGTH_SHORT).show();
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","La cantidad a enviar no puede exceder el límite establecido");
	     			   startService(intentemoslo);	
	     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                	// Vibrate for 400 milliseconds
	                	v.vibrate(400);	

	 			}else {
	 				if(qtycounted==0)
					{
	 					Toast.makeText(getApplicationContext(), "No se puede ingresar una cantidad igual a 0 o negativa.", Toast.LENGTH_SHORT).show();	 
						   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			   intentemoslo.putExtra("voz","No se puede ingresar una cantidad igual a 0 o negativa");  
		     			   startService(intentemoslo);	
		     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                	// Vibrate for 400 milliseconds
		                	v.vibrate(400);	
	 				}
	 				else
					{
	 						 					
	 					databaseHelper.UpdateTransferItem(nf.format(totalreceived).replace(",", ""),nf.format(newQtyDisponible).replace(",", ""), nf.format(newQtysobrante).replace(",", "") , ID);
	 		
	 			try{
	 				Cursor n = databaseHelper.getItemByID(ID);
	 				n.moveToFirst();
	 				
	 			 	String result = null;
	 			 	InputStream is = null;
	 			 	
	                //Double diferencia=Double.parseDouble(n.getString(7))-Double.parseDouble(n.getString(5));
	                NumberFormat format = NumberFormat.getInstance();
	                format.setMaximumFractionDigits(0);// set as you need
	        		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    		String dat = sd.format(new Date()); 
		    			    		
		    		String InventtransId = n.getString(1);
		    		String ItemID = n.getString(3);
		    		String qtyTransfer= n.getString(4);
		    		String qtyCounted = n.getString(5);
		    		String InventLocIDFrom = n.getString(6);
		    		String InventLocIDTo = n.getString(7);
		    		String Processed = n.getString(8);
		    		String Estatus =n.getString(9);
		    		String qtyAvailable =n.getString(11);
					String createddate =n.getString(12);
					String barcode =n.getString(13);
					String qtyremain=n.getString(14);
					String purchid=n.getString(16);
					String purchlinenum=n.getString(17);
					String config=n.getString(18);
					
					String configdat=config;
					if(configdat.charAt(0)=='B')
					{
						configdat=configdat.substring(1, configdat.length());
					}else
					{
						configdat="1";
					}
					
					Double qtyundscounted=Double.parseDouble(qtyCounted)*Double.parseDouble(configdat);
					Double qtyundstransfer=Double.parseDouble(qtyTransfer)*Double.parseDouble(configdat);
					qtyahoraun=qtyundscounted.toString();
					qtyahorab=qtyCounted;
					qtyremainf=qtyremain;
					itemidf=ItemID;
					transferidf=PONUMBER;
					inventtransidf=InventtransId;
		    		
	 			 	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	 			 	
	 			 	nameValuePairs.add(new BasicNameValuePair("INVENTTRANSID","'"+InventtransId+"'"));
	 			  	nameValuePairs.add(new BasicNameValuePair("TRANSFERID","'"+PONUMBER+"'"));
	 			    nameValuePairs.add(new BasicNameValuePair("ITEMID","'"+ItemID+"'"));
	 			  	nameValuePairs.add(new BasicNameValuePair("QTYTRANSFER","'"+qtyTransfer+"'"));
	 			    nameValuePairs.add(new BasicNameValuePair("QTYCOUNTED","'"+qtyCounted+"'"));
	 			    nameValuePairs.add(new BasicNameValuePair("INVENTLOCATIONIDFROM","'"+InventLocIDFrom.toUpperCase()+"'"));
	 			    nameValuePairs.add(new BasicNameValuePair("INVENTLOCATIONIDTO","'"+InventLocIDTo.toUpperCase()+"'"));
	 			    nameValuePairs.add(new BasicNameValuePair("TRANSDATEBEGIN","'"+COUNTINGSTARTED+"'"));
	 			    nameValuePairs.add(new BasicNameValuePair("TRANSDATE","'"+dat+"'"));
	 			  	nameValuePairs.add(new BasicNameValuePair("COUNTEDBY","'"+USERNAME+"'"));
	 			  	nameValuePairs.add(new BasicNameValuePair("PROCESSED","'"+Processed+"'"));
	 			    nameValuePairs.add(new BasicNameValuePair("TRANSFERSTATUS","'"+Estatus+"'"));
	 			    nameValuePairs.add(new BasicNameValuePair("DATAAREAID","'"+EMP2+"'"));
	 			    nameValuePairs.add(new BasicNameValuePair("QTYAVAILABLE",""+qtyAvailable+""));
					nameValuePairs.add(new BasicNameValuePair("CREATEDDATE","'"+createddate+"'"));
					nameValuePairs.add(new BasicNameValuePair("ITEMBARCODE","'"+barcode+"'"));
					nameValuePairs.add(new BasicNameValuePair("QTYREMAIN","'"+qtyremain+"'"));
					nameValuePairs.add(new BasicNameValuePair("PURCHID","'"+purchid+"'"));
					nameValuePairs.add(new BasicNameValuePair("PURCHLINENUM","'"+purchlinenum+"'"));
					nameValuePairs.add(new BasicNameValuePair("CONFIG","'"+config+"'"));
					nameValuePairs.add(new BasicNameValuePair("QTYTRANSFERUNDS","'"+qtyundstransfer+"'"));
					nameValuePairs.add(new BasicNameValuePair("QTYCOUNTEDUNDS","'"+qtyundscounted+"'"));


	 			    StrictMode.setThreadPolicy(policy); 
	 			        	//http post
	 			        	try{
	 			        	       HttpClient httpclient = new DefaultHttpClient();
	 			        	        HttpPost httppost2 = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/UpdateTransferList2.php");
	 			        	     	httppost2.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	 			        	        HttpResponse response = httpclient.execute(httppost2);
	 			        	        HttpEntity entity = response.getEntity();
	 			        	        is = entity.getContent();
	 			        	        Log.e("log_tag", "connection success ");
	 			        	       TERMINUS=true;  
	 			        	       //Si la consulta es exitosa el verificador se vuelve 1 para avanzar a la siguiente consulta. En caso de lo contrario vuelve a 0.
	 			        	      verificador=1;
	 			        	      //  Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
	 			        	   }
	 			        	catch(Exception e)
	 			        	{
	 			        		  TERMINUS=false;
	 			        	        Log.e("log_tag", "Error in http connection "+e.toString());
	 			        	        Toast.makeText(getApplicationContext(), "Error de conexión", Toast.LENGTH_SHORT).show();
	 			        	       verificador=0;
	 			        	}
	 			        	//convert response to string
	 			        	try{
	 			        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	 			        	        StringBuilder sb = new StringBuilder();
	 			        	        String line = null;
	 			        	        while ((line = reader.readLine()) != null) 
	 			        	        {
	 			        	                sb.append(line + "\n");
	 			        	        }
	 			        	        is.close();
	 			        	        result=sb.toString();
	 			        	}
	 			        	catch(Exception e)
	 			        	{
								TERMINUS=false;
	 			        	       Log.e("log_tag", "Error converting result "+e.toString());
	 			           	}
	 			        	try{
	 			        	            	JSONObject json_data = new JSONObject(result);
	 			        	            	
	 			        	                //CharSequence w= (CharSequence) json_data.get("re");
	 			        	  			//    Toast toasta=Toast.makeText(getApplicationContext(), w, 2000);
	 							  	      //  toasta.setGravity(Gravity.CENTER,0,0);
	 							  	    //    toasta.show();	
	 			        	     }
	 			        	catch(JSONException e)
	 			        	   {
	 			        	        Log.e("log_tag", "Error parsing data "+e.toString());
	 			        	     //   Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
	 			        	    }}catch(Exception e){	}

	 			if(verificador==1){
	 				
	 				/*Actualizacion de transferencia en el Enviar Ahora*/

					try{

						String resultf = null;
						InputStream isf = null;

						ArrayList<NameValuePair> nameValuePairs2 = new ArrayList<NameValuePair>();
						nameValuePairs2.add(new BasicNameValuePair("Transferid","'"+transferidf+"'"));
						nameValuePairs2.add(new BasicNameValuePair("Itemid","'"+itemidf+"'"));
						nameValuePairs2.add(new BasicNameValuePair("QtyShipNow",""+qtyahoraun+""));//Guarda unidades en inventtransferline
						nameValuePairs2.add(new BasicNameValuePair("LineNum","'"+LINENUM+"'"));
						//nameValuePairs2.add(new BasicNameValuePair("QtyReceiveNow",""+qtyahoraun+""));

						StrictMode.setThreadPolicy(policy);
						//http post
						try{
							HttpClient httpclient = new DefaultHttpClient();
							HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/UpdateTransferLineAX.php");
							httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
							HttpResponse response = httpclient.execute(httppost);
							HttpEntity entity = response.getEntity();
							isf = entity.getContent();
							Log.e("log_tag", "connection success ");
							TERMINUS=true;
							//Si la consulta es exitosa el verificador se vuelve 2 para avanzar a la siguiente consulta. En caso de lo contrario vuelve a 0.
							verificador=2;
							//  Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
						}
						catch(Exception e)
						{
							TERMINUS=false;
							Log.e("log_tag", "Error in http connection "+e.toString());
							Toast.makeText(getApplicationContext(), "Error de conexión", Toast.LENGTH_SHORT).show();
							verificador=0;
						}
						//convert response to string
						try{
							BufferedReader reader = new BufferedReader(new InputStreamReader(isf,"iso-8859-1"),8);
							StringBuilder sb = new StringBuilder();
							String line = null;
							while ((line = reader.readLine()) != null)
							{
								sb.append(line + "\n");
							}
							isf.close();
							resultf=sb.toString();
						}
						catch(Exception e)
						{
							Log.e("log_tag", "Error converting result "+e.toString());
						}
						try{
							JSONObject json_data = new JSONObject(resultf);

							//CharSequence w= (CharSequence) json_data.get("re");
							//    Toast toasta=Toast.makeText(getApplicationContext(), w, 2000);
							//  toasta.setGravity(Gravity.CENTER,0,0);
							//    toasta.show();
						}
						catch(JSONException e)
						{
							Log.e("log_tag", "Error parsing data "+e.toString());
							//   Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
						}}catch(Exception e){}
					/*FIN UPDATE TRANSFERLINE*/
				
	 				
	 			}else{
	 				Toast.makeText(getApplicationContext(), "Envío de Artículo fallido. Enviar Ahora no Actualizado.", Toast.LENGTH_SHORT).show();
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","No se pudo enviar Artículo");
	     				edittext.setText("0");
	     			   startService(intentemoslo);	
	     			   verificador=0;
	 			}
	 			
	 			if(verificador==2){
				
	 				/*Actualizacion de pedido compra con cantidad de envio */
					
					try
					{
						Cursor cursor2 = databaseHelper.getTransferItem(PONUMBER,itemidf,inventtransidf);
						int tam= cursor2.getCount();
						cursor2.moveToFirst();
						
						if(tam==0){Toast.makeText(getApplicationContext(), "no hay líneas de pedido por actualizar(Recibir Ahora).", Toast.LENGTH_SHORT).show();}
						else
						{
						int counterPO=0;	
							
						String idf = cursor2.getString(0);
						ID=idf;
						String lineapedidopo= cursor2.getString(17);
						String pedidof= cursor2.getString(16);
						/*--------------------------------------------------*/
						//Acumulador de Recibir ahora. Al enviar el total toma el remanente y le suma lo contado.
						double  qtyremain=Double.parseDouble(cursor2.getString(14));
						
						double newqtyb=qtyremain+Double.parseDouble(qtyahorab);
						
						String newqtybf = String.valueOf(newqtyb);
						//Método que quita los decimales.
						try{
							Double Qt = Double.parseDouble(newqtybf);
							NumberFormat nf4 = NumberFormat.getInstance();
							nf4.setMaximumFractionDigits(0);// set as you need
							newqtybf=nf4.format(Qt).replace(",", "");
						}catch(Exception e){}
						
						//Estructura que transforma a unidades los bultos contados para guardar en el Recibir Ahora.
						String configdat=cursor2.getString(18);
						if(configdat.charAt(0)=='B')
						{
							configdat=configdat.substring(1, configdat.length());
						}else
						{
							configdat="1";
						}
						
						Double qtyundscountedf=newqtyb*Double.parseDouble(configdat);
						
						
						try {
								
								String resultf = null;
								InputStream isf = null;

								ArrayList<NameValuePair> nameValuePairs2 = new ArrayList<NameValuePair>();
								nameValuePairs2.add(new BasicNameValuePair("QTYRECEIVED", "'" + newqtybf + "'"));
								nameValuePairs2.add(new BasicNameValuePair("PO", "'" + pedidof + "'"));
								nameValuePairs2.add(new BasicNameValuePair("EMP", "'" + EMP2 + "'"));
								nameValuePairs2.add(new BasicNameValuePair("ITEMID", "'" + itemidf + "'"));
								nameValuePairs2.add(new BasicNameValuePair("LINENUM", "'" + lineapedidopo + "'"));
								nameValuePairs2.add(new BasicNameValuePair("INVENTRECEIVEDNOW", "'" + qtyundscountedf.toString()+ "'"));

								StrictMode.setThreadPolicy(policy);
								//http post
								try {
									HttpClient httpclient2 = new DefaultHttpClient();
									HttpPost httppost2 = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/UpdatePurchLineAX.php");
									httppost2.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
									HttpResponse response = httpclient2.execute(httppost2);
									HttpEntity entity = response.getEntity();
									isf = entity.getContent();
									Log.e("log_tag", "connection success ");
									TERMINUS = true;
									counterPO++;
									
								} catch (Exception e) {
									TERMINUS = false;
									Log.e("log_tag", "Error in http connection " + e.toString());
									Toast.makeText(getApplicationContext(), "Error de conexión", Toast.LENGTH_SHORT).show();
								}
								//convert response to string
								try {
									BufferedReader reader = new BufferedReader(new InputStreamReader(isf, "iso-8859-1"), 8);
									StringBuilder sb = new StringBuilder();
									String line = null;
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									isf.close();
									resultf = sb.toString();
								} catch (Exception e) {
									//TERMINUS = false;
									Log.e("log_tag", "Error converting result " + e.toString());
								}
								try 
								{
									JSONObject json_data = new JSONObject(resultf);
								} 
								catch (JSONException e) 
								{
									Log.e("log_tag", "Error parsing data " + e.toString());
									//   Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
								}


							}catch (Exception e) {}
							
						}

					}catch(Exception exc){}
					
					/*FIN UPDATE PURCHID*/

	 			}else{
	 				Toast.makeText(getApplicationContext(), "Envío de Artículo fallido. Recibir Ahora no Actualizado", Toast.LENGTH_SHORT).show();
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","No se pudo enviar Artículo");
	     				edittext.setText("0");
	     			   startService(intentemoslo);	
	     			   verificador=0;
	     			   
	 			}
	 				
	 					 					        	
	 			 if(TERMINUS==true){
		 		       Toast.makeText(getApplicationContext(), "Artículo enviado.", Toast.LENGTH_SHORT).show();
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","Artículo enviado");
	     				edittext.setText("0");
	     				finish();
	     			   startService(intentemoslo);	
		 			 }else
		 			 {
		 				Toast.makeText(getApplicationContext(), "No se pudo enviar Artículo. Recibir Ahora 0.", Toast.LENGTH_SHORT).show();
						   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			   intentemoslo.putExtra("voz","No se pudo enviar Artículo");
		     				edittext.setText("0");
		     			   startService(intentemoslo);	
		 			 }


	          	
	         }

   			try {
   		
   			} catch (Exception e) {
   			    e.printStackTrace();

   			}
		
   			if(TERMINUS){     	
 		 		 this.recreate();
 	     			}else{
 	     				
 	     				if(qtycounted==0){
 	     				Toast.makeText(getApplicationContext(), "No se puede ingresar una cantidad igual a 0 o negativa.", Toast.LENGTH_SHORT).show();	 
						   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			   intentemoslo.putExtra("voz","No se puede ingresar una cantidad igual a 0 o negativa");  
		     			   startService(intentemoslo);	
		     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                	// Vibrate for 400 milliseconds
		                	v.vibrate(400);	
		                	
 	     				}else{
 	     				 new AlertDialog.Builder(context)
 		     			    .setTitle("Error de conexión")
 		     			    .setMessage(" Verifique que está conectado a la red e intente de nuevo.")
 		     			    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
 		     			        public void onClick(DialogInterface dialog, int which) { 
 		     			            // continue with delete
 		     			        }
 		     			     })
 		     			    .setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
 		     			        public void onClick(DialogInterface dialog, int which) { 
 		     			            // do nothing
 		     			        }
 		     			     })
 		     			    .setIcon(android.R.drawable.ic_dialog_alert)
 		     			     .show();
 		     				 
 		     				 Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
 			     			   intentemoslo.putExtra("voz","Verifique que está conectado a la red e intente de nuevo.");
 			     			   startService(intentemoslo);	
 			     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
 			                	// Vibrate for 400 milliseconds
 			                	v.vibrate(400);
 	     			}}}
	 		}else{	

			       	Toast.makeText(getApplicationContext(), "Digite la cantidad para avanzar.", Toast.LENGTH_SHORT).show();	 
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","Digite la cantidad para avanzar");  
	     			   startService(intentemoslo);	
	     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                	// Vibrate for 400 milliseconds
	                	v.vibrate(400);
	         }
	         }}

		private boolean hasContent(EditText et) {
		       return (et.getText().toString().trim().length() > 0);
		}

	@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
				
			    	execute=1;
			    	
			        String key = KeyEvent.keyCodeToString(keyCode);
			        
			        // key will be something like "KEYCODE_A" - extract the "A"

			        // use pattern to convert int keycode to some character
			        Matcher matcher = KEYCODE_PATTERN.matcher(key);
			        
			        if (matcher.matches()) {
			            // append character to textview
			        	 Scanning=Scanning+matcher.group(1);
			        //	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexiï¿½n de VPN.", Toast.LENGTH_SHORT).show();
			          //
			        }
			    	new CountDownTimer(1000, 1000) {       
						   public void onTick(long millisUntilFinished) {          
						}       

						public void onFinish() {   
							if(execute==1){
								execute=0;
							    escaneo=Scanning;	
							    if(Scanning.equals("")){}
							    else{
									  if(COUNTER==0){
							             TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
							             Cursor cursor = databaseHelper.getTransferItemBarcode(PONUMBER,Scanning);
							     	     if(cursor.getCount()>0){
							     	     cursor.moveToFirst();
							     	     ID= cursor.getString(0);
							     	     TextView qtyreceived = (TextView) findViewById(R.id.article);
							     	     TextView qty = (TextView) findViewById(R.id.ofqty);

											 qtyreceived.setText(cursor.getString(5));//6 QTYCOUNTED
											 String UnidDisp= cursor.getString(11);//15  RESERVPHYSICAL
							     	     if(UnidDisp.equals("null")){
							     	    	UnidDisp="0";
							     	     } 
							     	     
							     	     if(UnidDisp.equals("1"))
							      	    {
							  	    		qty.setText("de "+UnidDisp+ " bulto "+CONFIG+ " disponible");
							  	    	
							  	    }else
							  	    {
							  	    	     qty.setText("de "+UnidDisp+ " bultos "+CONFIG+ " disponibles");
							  	    }
							      	   
							     	   buscarheader.setText(cursor.getString(3));//ITEMID
							     	   buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
							     	    	
							    	    EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);

							    		Double cant = Double.parseDouble(cursor.getString(4));//5
							      		Double cantrec = Double.parseDouble(cursor.getString(5));//6
							      		Double remaining= cant-cantrec;
							      		NumberFormat nf = NumberFormat.getInstance();

							    	        nf.setMaximumFractionDigits(0);// set as you need
							      		  myEditText.setText(nf.format(remaining));
							              myEditText.setClickable(true);
							              //myEditText.setFocusable(true);
							              //myEditText.setFocusableInTouchMode(true);
							              //myEditText.requestFocus();
							     		    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							      		COUNTINGSTARTED = sd.format(new Date()); 
							      		COUNTER++;
							     	     }else{
							     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
							     	   Toast.makeText(getBaseContext(), "No se pudo cargar Artículo. Intente nuevamente.", Toast.LENGTH_LONG).show();
							     	  	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
							     	  	// Vibrate for 400 milliseconds
							     	  	v.vibrate(400);
							     	        COUNTER=0;
							     	     }
							    	     
							      	      Scanning="";
									  }
									  else if(COUNTER==1){
									  
										  StrictMode.setThreadPolicy(policy); 
										  TextView bodDestino = (TextView)findViewById(R.id.destino);
						                	databaseHelper2 = new WarehouseBarcodeDataBaseHelper(context.getApplicationContext()); 
						                		try{
						                			String result = null;
						                	    	InputStream is = null;
						                	  
						                	    	String v1 = "'"+Scanning+"'";
						                			String v2 = "'"+EMP2+"'";
						                			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
						                		
						                	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
						                	     	nameValuePairs.add(new BasicNameValuePair("BARCODE",v1));
						                	       	nameValuePairs.add(new BasicNameValuePair("EMPRESA",v2));

						                	//apartir de aqui carga ruta
						                		try
						                		{
						                	    	        HttpClient httpclient = new DefaultHttpClient();
						                	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getWarehouseBarcode.php");
						                	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
						                	    	        HttpResponse response = httpclient.execute(httppost); 
						                	    	        HttpEntity entity = response.getEntity();
						                	    	        is = entity.getContent();
						                	    	        Log.e("log_tag", "connection success ");
						                	    	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
						                		}
						                	catch(Exception e)
						                		{
						                	    	        Log.e("log_tag", "Error in http connection "+e.toString());
						                	    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
						                	    	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
						                		}
						                	    	//convert response to string
						                		try{
						                			
						                	    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
						                	    	        StringBuilder sb = new StringBuilder();
						                	    	        String line = null;
						                	    	        while ((line = reader.readLine()) != null) 
						                	    	        {
						                	    	                sb.append(line + "\n");
						                	    	        }
						                	    	        is.close();
						                	    	        result=sb.toString();
						                		}
						                		catch(Exception e)
						                		{
						                	    	       Log.e("log_tag", "Error converting result "+e.toString());
						                		}
						                	int counter=0;
						                	    	//parse json data
						                	    	try{
						                	           databaseHelper2.deleteAllData();

						                	    	 	JSONArray jArray = new JSONArray(result);
						                	    		for(int i=0;i<jArray.length();i++)  
						                	            {
						                	    			try{
						                	    		   	JSONObject no = jArray.getJSONObject(i);
						                	    		    String inventlocationid=no.getString("INVENTLOCATIONID");
						                	    		    String barcode=no.getString("BARCODE");
						                	    		    String dataareaid=no.getString("DATAAREAID");
						                	    		   
						                		            NumberFormat nf = NumberFormat.getInstance();
						                		            nf.setMaximumFractionDigits(0);// set as you need
						                	               
						                		            BodResult = inventlocationid;
						                		            
						                	            	databaseHelper2.saveWarehouseBarcode(inventlocationid.toUpperCase(),barcode,dataareaid);

						                		            counter++;
						                		   
						                	    			}catch(Exception e)
						                		          	{ 
						                	    				 Log.e("log_tag", "Error cargando datos "+e.toString());
						                		          	}
						                		            }
						                	    	}
						                	    	catch(JSONException e)
						                	    	{
						                	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
						                	     	} catch (IllegalArgumentException e) {
						                				// TODO Auto-generated catch block
						                				e.printStackTrace();
						                			} 	
						                			}catch(Exception e)
						                	    	{
						                		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
						                		}
						                		 EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
						                		String dest = "";
						                		TextView DES = (TextView)findViewById(R.id.destino); 
						                		Cursor x =databaseHelper2.getAllWarehouseBarcodeLines(escaneo);
						                		if(x.getCount()>0 ){
						                			if(BodResult.equals(BODDEST))
						                			{
						                			x.moveToFirst();
						                			dest=x.getString(1);
						                			DES.setText(dest);
						                			  myEditText.setFocusable(true);
										              myEditText.setFocusableInTouchMode(true);
										              myEditText.requestFocus();
						                			DES.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
						                			COUNTER=2;
						                			}else
						                			{
						                				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
							                          	// Vibrate for 400 milliseconds
							                          	v.vibrate(400);
							                          	bodDestino.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
								                	    Toast.makeText(getBaseContext(), "Bodega de destino incorrecta. Intente nuevamente.", Toast.LENGTH_LONG).show();	
								                	    COUNTER=1;
						                			}
						                		}else{
						                			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
						                          	// Vibrate for 400 milliseconds
						                          	v.vibrate(400);
						                          	bodDestino.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
							                	    Toast.makeText(getBaseContext(), "No se pudo cargar bodega de destino. Intente nuevamente.", Toast.LENGTH_LONG).show();	
							                	    COUNTER=1;
						                		}
									  }
									  
									  Scanning="";
									  
							}
						
						}
						}
						}.start();  
			        
			        return super.onKeyDown(keyCode, event);
			    }
	

	 
}
