package com.example.waoperations.Transference;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.example.waoperations.FontsOverride;
import com.example.waoperations.R;
import com.example.waoperations.VoiceHelper;
import com.example.waoperations.Shipping.ShippingAdapterTransfer;
import com.example.waoperations.Shipping.ShippingTransferDatabaseHelper2;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.StrictMode;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TransferenceZurquiDetail 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,ITEM;
	final Context context = this;
	public String ID, empresa,BodResult;
	public String EXISTENTE,LOC,SKU,DATAAREAID,OFQTY,COUNTINGSTARTED,USERNAME,BARCODE,INVTID,SHIPID,LOCID,CONFIG,PED;
	private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
	public String Scanning="";
	public String escaneo="";
	public String configuracion= " ";
	public double cantunidades=0;
	public int execute=0;
	public EditText ED;
	public int timerstarted=0;
	public Boolean timercompleted=false;
	TransferenceAdapter1 newTransferenciasAdapter;
	private TextView tvTexto;
	private TransferenceDataBaseHelperZ databaseHelperZ;
	private WarehouseBarcodeDataBaseHelper databaseHelper2;
	private ShippingTransferDatabaseHelper2 databaseHelperShip;
	private TransferenceDataBaseHelperPO databaseHelperPO;
	private CrossDockingDataBaseHelper dataBaseHelperCrsDkc;

		ShippingAdapterTransfer newShippingAdapterTransfer;


		public String purchidf="";
		public String itemidf="";
		public String qtyremainf="";
		public String qtyahoraf="";
		public String totalqty="";
		public String inventtransidf="";


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
		setContentView(R.layout.watransferitemzurqui);
		databaseHelperZ = new TransferenceDataBaseHelperZ(this.getApplicationContext());
		databaseHelperShip = new ShippingTransferDatabaseHelper2(this.getApplicationContext());
		databaseHelperPO = new TransferenceDataBaseHelperPO(this.getApplicationContext());
		//dataBaseHelperCrsDkc = new CrossDockingDataBaseHelper(this.getApplicationContext());
		
	  ActionBar actionBar = getActionBar();
	  actionBar.hide();
	  // more stuff here...
	  actionBar.setSubtitle("Transfer Zurquí");
	  actionBar.setTitle("Warehouse");
	  actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
	  actionBar.setDisplayShowTitleEnabled(false);  // required to force redraw, without, gray color
	  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.CONFIG = intent.getStringExtra("CONFIG");
		this.ITEM = intent.getStringExtra("ITEM");
		this.PED = intent.getStringExtra("PED");
		
		configuracion = 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.setText(ITEMID);
	  
	  //TextView bodDestino1 = (TextView)findViewById(R.id.destino);
	  //bodDestino1.setText(BODDEST);
	  
      Cursor cursor = databaseHelperZ.getTransferItem(PED,ITEM.toUpperCase(),INVTID);
		//Cursor p = databaseHelperShip.getItemByID();

	     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(6));//6 QTYCOUNTED
		 String UnidDisp= cursor.getString(11);//15  RESERVPHYSICAL
	     if(UnidDisp.equals("")){
	    	UnidDisp="0";
	     }
	     
	     if(UnidDisp.equals("1"))
	 	    {
	 	    		qty.setText("de "+UnidDisp+ " bulto "+configuracion+ " disponible");
	 	    }else
	 	    {
	 	    	     qty.setText("de "+UnidDisp+ " bultos "+configuracion+ " disponibles");
	 	    }
	     view.setText(cursor.getString(4));//ITEMID
	     TextView bodDestino1 = (TextView)findViewById(R.id.destino);
		 bodDestino1.setText(BODDEST);
		 
		 view.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
		 bodDestino1.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
		 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 COUNTINGSTARTED = sd.format(new Date()); 
		 COUNTER=2;
	        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);

			Double cant = Double.parseDouble(cursor.getString(5));//5 QTYTRANSFER
	  		Double cantrec = Double.parseDouble(cursor.getString(6));//6 QTYCOUNTED
	  		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();
       
	  
	     }
	  

		/*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 = databaseHelperZ.getAllTransferenciasLines();
	          
		            while(m.moveToNext())	
		            {
		            	listItems.add(m.getString(4));
		            }
	          
		        ArrayAdapter adapter = new ArrayAdapter<String>(TransferenceZurquiDetail.this, android.R.layout.simple_list_item_activated_1, listItems);
	         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

	         // Create an ArrayAdapter using the string array and a default spinner layout
	         // Specify the layout to use when the list of choices appears
	         // Apply the adapter to the spinner
	        
	         
			  text.setAdapter(adapter);
	          alert.setView(text);
	          input.selectAll();
	      	alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	      	public void onClick(DialogInterface dialog, int whichButton) {
	      	//You will get as string input data in this variable.
	      	// here we convert the input to a string and show in a toast.
	      		
	    	    String srt = text.getEditableText().toString().toUpperCase();
	          Cursor cursor = databaseHelperZ.getTransferItem(PONUMBER,srt,INVTID);
				//Cursor p = databaseHelperShip.getItemByID();

	 	     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(6));//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");
	 	    }
	 	    
	 	     view.setText(cursor.getString(4));//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(5));//5 QTYTRANSFER
		  		Double cantrec = Double.parseDouble(cursor.getString(6));//6 QTYCOUNTED
		  		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()); 
	 	     }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();
      
	   }// 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) {
	      // Handle presses on the action bar items
		  
	  	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 = databaseHelperZ.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(6));//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(4));//ITEMID
						 buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));

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

						 Double cant = Double.parseDouble(cursor.getString(5));//5
						 Double cantrec = Double.parseDouble(cursor.getString(6));//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://10.10.100.13/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="";
			 }


	  	
	  		 
		  } else if (id == R.id.add) {
			  Toast.makeText(getBaseContext(), "Registrar.", Toast.LENGTH_LONG).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 = databaseHelperZ.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(6));//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(4));

		    	   	 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://10.10.100.13/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){
		        	 

		        	//ACÁ VA LA NUEVA REVISIÓN 

		        Boolean TERMINUS=false;
		 		if(this.hasContent(edittext)==true){
		 		
		 			Cursor po = databaseHelperZ.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.", Toast.LENGTH_SHORT).show();	 
							   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
			     			   intentemoslo.putExtra("voz","No se puede ingresar una cantidad igual a 0");  
			     			   startService(intentemoslo);	
			     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			                	// Vibrate for 400 milliseconds
			                	v.vibrate(400);	
		 				}
		 				else
						{
		 						 					
		 					databaseHelperZ.UpdateTransferItem(nf.format(totalreceived).replace(",", ""),nf.format(newQtyDisponible).replace(",", ""), nf.format(newQtysobrante).replace(",", "") , ID);
		 		
		 			try{
		 				Cursor n = databaseHelperZ.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 purchid=n.getString(2);
			    		String ShippingID = n.getString(3);
			    		String ItemID = n.getString(4);
			    		String qtyTransfer= n.getString(5);
			    		String qtyCounted = n.getString(6);
			    		String dataareaidto = n.getString(7);
			    		String InventLocIDTo = n.getString(8);
			    		String Processed = n.getString(9);
			    		String Estatus =n.getString(10);
			    		String qtyAvailable =n.getString(11);
						String barcode =n.getString(12);
						String qtyremain=n.getString(13);
						String wmslocationid=n.getString(14);
						String purchunit=n.getString(15);
						String qtyunds="0";

						qtyahoraf=qtyCounted;
						qtyremainf=qtyremain;
						itemidf=ItemID;
						purchidf=PONUMBER;
						INVTID=InventtransId;
						SHIPID=ShippingID;
						LOCID=InventLocIDTo;			
						String punit="";

						if(purchunit.charAt(0)=='B')
						{
							punit=purchunit.substring(1, purchunit.length());
						}else
						{
							punit="1";
						}
						
						cantunidades= Double.parseDouble(qtyCounted) *  Double.parseDouble(punit);
						qtyunds =  String.valueOf(cantunidades); 
			    		
		 			 	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		 			 	
		 			 	nameValuePairs.add(new BasicNameValuePair("INVENTTRANSID","'"+InventtransId+"'"));
		 			  	nameValuePairs.add(new BasicNameValuePair("PURCHID","'"+purchid+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("ITEMID","'"+ItemID+"'"));
		 			  	nameValuePairs.add(new BasicNameValuePair("QTYTRANSFER","'"+qtyTransfer+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("QTYCOUNTED","'"+qtyCounted+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("DATAAREAIDTO","'"+dataareaidto+"'"));
		 			    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("QTYAVAILABLE",""+qtyAvailable+""));
						nameValuePairs.add(new BasicNameValuePair("ITEMBARCODE","'"+barcode+"'"));
						nameValuePairs.add(new BasicNameValuePair("QTYREMAIN","'"+qtyremain+"'"));
						nameValuePairs.add(new BasicNameValuePair("SHIPPINGID","'"+ShippingID+"'"));
						nameValuePairs.add(new BasicNameValuePair("WMSLOCATIONID","'"+wmslocationid+"'"));
						nameValuePairs.add(new BasicNameValuePair("QTYUNDS","'"+qtyunds+"'"));
						nameValuePairs.add(new BasicNameValuePair("PURCHUNIT","'"+purchunit+"'"));

		 			    StrictMode.setThreadPolicy(policy); 
		 			        	//http post
		 			        	try{
		 			        	       HttpClient httpclient = new DefaultHttpClient();
		 			        	        HttpPost httppost2 = new HttpPost("http://10.10.100.13/UpdateTransferListZ.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;  
		 			        	      //  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();

		 			        	}
		 			        	//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){	}


							
							
							/*Actualizacion de pedido compra con cantidad de envio */

							try{
							Cursor cursor2 =databaseHelperPO.getAllTransferenciasPOLines();
							
							int tam= cursor2.getCount();

							cursor2.moveToFirst();
							String idf = cursor2.getString(0);
							String itid;
							Double pendiente;
							Double totalqtyunds;
							String unitconvert;
							String ped;
							
							if(tam==0){Toast.makeText(getApplicationContext(), "no hay registros en pedidos", Toast.LENGTH_SHORT).show();}
							else {

								int counterPO=0;
								TERMINUS = false;
								
								for(int i=0;i<cursor2.getCount();i++){
									
									idf = cursor2.getString(0);
									int processed= Integer.parseInt(cursor2.getString(12));
									
									switch(processed){
											
									case 0:
									
								 	totalqtyunds=Double.parseDouble(cursor2.getString(4));
									totalqty = cursor2.getString(3);
									ped = cursor2.getString(1);

								if((Double.parseDouble(qtyahoraf)==Double.parseDouble(totalqty) && counterPO==0)) {
									
									pendiente= Double.parseDouble(cursor2.getString(3));
									itid=cursor2.getString(11);
					
									if( pendiente==Double.parseDouble(totalqty) && counterPO==0) {
										
										try {
											
											String resultf = null;
											InputStream isf = null;

											ArrayList<NameValuePair> nameValuePairs2 = new ArrayList<NameValuePair>();
											nameValuePairs2.add(new BasicNameValuePair("QTYRECEIVED", "'" + totalqty + "'"));
											nameValuePairs2.add(new BasicNameValuePair("PO", "'" + ped + "'"));
											nameValuePairs2.add(new BasicNameValuePair("EMP", "'" + EMP2 + "'"));
											nameValuePairs2.add(new BasicNameValuePair("ITEMID", "'" + itemidf + "'"));
											nameValuePairs2.add(new BasicNameValuePair("LINENUM", "'" + itid + "'"));
											nameValuePairs2.add(new BasicNameValuePair("INVENTRECEIVEDNOW", "'" + totalqtyunds + "'"));

											StrictMode.setThreadPolicy(policy);
											//http post
											try {
												HttpClient httpclient2 = new DefaultHttpClient();
												HttpPost httppost2 = new HttpPost("http://10.10.100.13/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;
												cursor2.moveToNext();
												
												counterPO++;
												databaseHelperPO.UpdatePurchLine2(idf);
												databaseHelperZ.UpdateProcessed(ID);
												//  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();
											}
											//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) {}
										
										
									}else{
											cursor2.moveToNext();
									}

								}else{
									
									if(Double.parseDouble(qtyahoraf)<Double.parseDouble(totalqty) && counterPO==0)
									{
										unitconvert=cursor2.getString(5);
										itid=cursor2.getString(11);
										if(unitconvert.charAt(0)=='B')
										{
											unitconvert=unitconvert.substring(1, unitconvert.length());
										}else
										{
											unitconvert="1";
										}
										
										double totalqty2=Double.parseDouble(qtyahoraf)*Double.parseDouble(unitconvert);
										
										try {
											
											String resultf = null;
											InputStream isf = null;

											ArrayList<NameValuePair> nameValuePairs2 = new ArrayList<NameValuePair>();
											nameValuePairs2.add(new BasicNameValuePair("QTYRECEIVED", "'" + qtyahoraf + "'"));
											nameValuePairs2.add(new BasicNameValuePair("PO", "'" + ped + "'"));
											nameValuePairs2.add(new BasicNameValuePair("EMP", "'" + EMP2 + "'"));
											nameValuePairs2.add(new BasicNameValuePair("ITEMID", "'" + itemidf + "'"));
											nameValuePairs2.add(new BasicNameValuePair("LINENUM", "'" + itid + "'"));
											nameValuePairs2.add(new BasicNameValuePair("INVENTRECEIVEDNOW", "'" + totalqty2 + "'"));

											StrictMode.setThreadPolicy(policy);
											//http post
											try {
												HttpClient httpclient2 = new DefaultHttpClient();
												HttpPost httppost2 = new HttpPost("http://10.10.100.13/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;
												cursor2.moveToNext();
												
												counterPO++;
												databaseHelperPO.UpdatePurchLine(idf);
												//  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();
											}
											//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) {}
										
									}else
									{
									cursor2.moveToNext();
									}
								}
								break;
								
								
									case 1:
										
										double qtyrece;
										double qtyparcial;
										totalqtyunds=Double.parseDouble(cursor2.getString(4));
										ped = cursor2.getString(1);
										  
										if((Double.parseDouble(qtyahoraf)<Double.parseDouble(totalqty) && counterPO==0)) {
											
											qtyrece= Double.parseDouble(cursor2.getString(6));
											pendiente= Double.parseDouble(cursor2.getString(3));
											
											unitconvert=cursor2.getString(5);
											itid=cursor2.getString(11);
											
											if(unitconvert.charAt(0)=='B')
											{
												unitconvert=unitconvert.substring(1, unitconvert.length());
											}else
											{
												unitconvert="1";
											}
											
											qtyparcial=Double.parseDouble(qtyahoraf)*Double.parseDouble(unitconvert);
											double totalqty2=qtyrece+qtyparcial;
							
											if(pendiente==totalqty2 && counterPO==0) {

												try {
													
													String resultf = null;
													InputStream isf = null;

													ArrayList<NameValuePair> nameValuePairs2 = new ArrayList<NameValuePair>();
													nameValuePairs2.add(new BasicNameValuePair("QTYRECEIVED", "'" + qtyahoraf + "'"));
													nameValuePairs2.add(new BasicNameValuePair("PO", "'" + ped + "'"));
													nameValuePairs2.add(new BasicNameValuePair("EMP", "'" + EMP2 + "'"));
													nameValuePairs2.add(new BasicNameValuePair("ITEMID", "'" + itemidf + "'"));
													nameValuePairs2.add(new BasicNameValuePair("LINENUM", "'" + itid + "'"));
													nameValuePairs2.add(new BasicNameValuePair("INVENTRECEIVEDNOW", "'" + totalqty2 + "'"));

													StrictMode.setThreadPolicy(policy);
													//http post
													try {
														HttpClient httpclient2 = new DefaultHttpClient();
														HttpPost httppost2 = new HttpPost("http://10.10.100.13/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;
														cursor2.moveToNext();
														
														counterPO++;
														databaseHelperPO.UpdatePurchLine2(idf);
														//  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();
													}
													//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) {}
												
												
											}else{
												cursor2.moveToNext();
											}

										}else{
											cursor2.moveToNext();
										}
										break;
										
									case 2:
										cursor2.moveToNext();
										break;
									}

								}
							}

							
						}catch(Exception ex){
							
						}
							
							
							try{

								String resultc = null;
								InputStream isc = null;

								ArrayList<NameValuePair> nameValuePairs2 = new ArrayList<NameValuePair>();
								nameValuePairs2.add(new BasicNameValuePair("INVENTTRANSID","'"+INVTID+"'"));
								nameValuePairs2.add(new BasicNameValuePair("PURCHID","'"+purchidf+"'"));
								nameValuePairs2.add(new BasicNameValuePair("ITEMID","'"+itemidf+"'"));
								nameValuePairs2.add(new BasicNameValuePair("SHIPMENTID","'"+SHIPID+"'"));
								nameValuePairs2.add(new BasicNameValuePair("INVENTLOCATIONIDTO","'"+LOCID+"'"));

								StrictMode.setThreadPolicy(policy);
								//http post
								try{
									HttpClient httpclient = new DefaultHttpClient();
									HttpPost httppost = new HttpPost("http://10.10.100.13/UpdateCrossDockingZ.php");
									httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
									HttpResponse response = httpclient.execute(httppost);
									HttpEntity entity = response.getEntity();
									isc = entity.getContent();
									Log.e("log_tag", "connection success ");
									TERMINUS=true;
									//  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();
								}
								//convert response to string
								try{
									BufferedReader reader = new BufferedReader(new InputStreamReader(isc,"iso-8859-1"),8);
									StringBuilder sb = new StringBuilder();
									String line = null;
									while ((line = reader.readLine()) != null)
									{
										sb.append(line + "\n");
									}
									isc.close();
									resultc=sb.toString();
								}
								catch(Exception e)
								{
									Log.e("log_tag", "Error converting result "+e.toString());
								}
								try{
									JSONObject json_data = new JSONObject(resultc);

									//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(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.", 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{
		          			
		          			String result = null;
		          	    	InputStream is = null;
		          	  
		          	    	String v1 = "'"+PONUMBER+"'";
		          	    	String v2 = "'"+EMP2+"'"; 
		          	    	
		          			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");

		          	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		          	     	nameValuePairs.add(new BasicNameValuePair("TRANSFERID",v1));
		          	    	nameValuePairs.add(new BasicNameValuePair("DATAAREAID",v2));
		          	    	
		          	//apartir de aqui carga ruta
		          		try{
		          	    	        HttpClient httpclient = new DefaultHttpClient();
		          	    	        HttpPost httppost = new HttpPost("http://10.10.100.13/getTransferenciasNotProcessedListByTransferID.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{
		          	            //databaseHelper.deleteAllData();

		          	    	 	JSONArray jArray = new JSONArray(result);
		          	    		for(int i=0;i<jArray.length();i++)  
		          	            {
		          	    			try{
		          	    		   	JSONObject no = jArray.getJSONObject(i);

		          	    	        String COUNTED=no.getString("QTYCOUNTED");

		          	    		    try{
		          	        		    Double Qt = Double.parseDouble(COUNTED);
		          	        		    NumberFormat nf3 = NumberFormat.getInstance();
		          		 	            nf3.setMaximumFractionDigits(0);// set as you need
		          		 	            COUNTED=nf3.format(Qt).replace(",", "");
		          	        		    
		          	        		}catch(Exception e){}

										String AVAILABLE=no.getString("QTYAVAILABLE");
										// Disponible=AVAILABLE;

										try{
											Double Qt = Double.parseDouble(AVAILABLE);
											NumberFormat nf3 = NumberFormat.getInstance();
											nf3.setMaximumFractionDigits(0);// set as you need
											AVAILABLE=nf3.format(Qt).replace(",", "");

										}catch(Exception e){}

										String RESERVADA=no.getString("QTYREMAIN");

										try{
											Double Qt = Double.parseDouble(RESERVADA);
											NumberFormat nf4 = NumberFormat.getInstance();
											nf4.setMaximumFractionDigits(0);// set as you need
											RESERVADA=nf4.format(Qt).replace(",", "");

										}catch(Exception e){}


										String inventtransid=no.getString("INVENTTRANSID");
										String itemid=no.getString("ITEMID");
										NumberFormat nf2 = NumberFormat.getInstance();
										nf2.setMaximumFractionDigits(0);// set as you need
										Cursor xyz =databaseHelperZ.getTransferItemDetail(PONUMBER,inventtransid,itemid);
										if(xyz.getCount()>0)
										{
											xyz.moveToFirst();
											String id1 = xyz.getString(0);
											databaseHelperZ.UpdateTransferItem(COUNTED, AVAILABLE, RESERVADA, id1);
										}
		          		            counter++;
		          	    			}catch(Exception e)
		          		          	{
		          		          	}
		          		            	 }
		          	  
		          	    	}
		          	    	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.");
		          		}
		         }

	   			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.", Toast.LENGTH_SHORT).show();	 
							   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
			     			   intentemoslo.putExtra("voz","No se puede ingresar una cantidad igual a 0");  
			     			   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 = databaseHelperZ.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(6));//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(4));//ITEMID
								     	   buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
								     	    	
								    	    EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);

								    		Double cant = Double.parseDouble(cursor.getString(5));//5
								      		Double cantrec = Double.parseDouble(cursor.getString(6));//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://10.10.100.13/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);
				    }
		
		/* public void onBackPressed()
		    {
			 
			 /* new AlertDialog.Builder(this)
		        .setIcon(android.R.drawable.ic_dialog_alert)
		        .setTitle("Salir de la Transferencia...")
		        .setMessage("Estás seguro que deseas salir del detalle de la Transferencia??")
		        .setPositiveButton("Aceptar", new DialogInterface.OnClickListener()
		    {
		        @Override
		        public void onClick(DialogInterface dialog, int which) {
		            finish();    
		        }

		    })
		    .setNegativeButton("Cancelar", null)
		    .show();
			 	    */
		    //}
		    

		 
		 

	
	

}
