package com.example.waoperations.PutAway;




import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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.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.R;
import com.example.waoperations.UserPermissionsDatabaseHelper;
import com.example.waoperations.VoiceHelper;
import com.example.waoperations.Inventory.InventoryAdapter;
import com.example.waoperations.Inventory.InventoryAdapterSummary;
import com.example.waoperations.Inventory.InventoryDatabaseHelper;
import com.example.waoperations.R.color;
import com.example.waoperations.R.id;
import com.example.waoperations.R.layout;
import com.example.waoperations.R.menu;


import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
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.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.speech.RecognizerIntent;
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.ViewGroup;
import android.widget.ArrayAdapter;
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 PutAwayDetail extends Activity {
	  private static final int REQUEST_CODE = 1234;
	  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	  public int COUNTER =0;
	  public String PONUMBER;
	  public String LOC,SKU,DATAAREAID,OFQTY,COUNTINGSTARTED,USERNAME,ORDERID,ROUTEID,INVENTDIMID,INVENTRANS,NOMBRESKU,NOMBREPOS;
	  public String ID;
	  public String LOCATION;
	  public String TYPE;
	  public double QTY,QTYLOCATED;
	  public TextView POSICION,ARTICULO,CANTIDAD;
	  public EditText ED;
	  final Context context = this;
	  InventoryAdapterSummary newInventoryAdapter;
      public int execute=0;
      public int timerstarted=0;
      public String Scanning="";
      public Boolean timercompleted=false;
      private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
      private InventoryDatabaseHelper InvDatabaseHelper;
	  PutAwayAdapter newPutAwayAdapter;
	  private PutAwayDatabaseHelper databaseHelper;
	  
	  @Override
	    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
		setContentView(R.layout.waputawayitem);
		databaseHelper = new PutAwayDatabaseHelper(this.getApplicationContext()); 
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    actionBar.setSubtitle("Putaway");
	    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.DATAAREAID = intent.getStringExtra("DATA");
		this.USERNAME = intent.getStringExtra("USER");
        EditText edittext = (EditText) this.findViewById(R.id.qtyamount);
	    
        edittext.setText("");

        edittext.setClickable(false);
        edittext.setFocusable(false);
		
	  
    	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		COUNTINGSTARTED = sd.format(new Date()); 
	    POSICION = (TextView) this.findViewById(R.id.buscarheader);
	    ARTICULO = (TextView) this.findViewById(R.id.article);
	    CANTIDAD = (TextView) this.findViewById(R.id.ofqty);
	    ED = (EditText) this.findViewById(R.id.qtyamount);
		InvDatabaseHelper = new InventoryDatabaseHelper(this.getApplicationContext()); 
		InvDatabaseHelper.deleteAllData();
	    
	    this.ID="";
	    this.SKU="";
	    this.LOCATION="";
			
	    String[] paises = new String[]{"KR","CN","US","MX","GB","SV","TW","IT","DE","PL","IN","RU","IL","MS","CZ","BR","ID","FR","PL","CA","AR","CH","CY","MA","TR","at","ZA","ES","CO","JP","NL","TN","TH","tu","UA","UK","bg","IS","MY","BU","AU","RS","BA","VN","BE"};
		Spinner equipment = (Spinner) findViewById(R.id.countries);
		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, paises);
		
		// Specify the layout to use when the list of choices appears
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// Apply the adapter to the spinner
		equipment.setAdapter(adapter2);
	   
	   
	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("Validación manual"); //Set Alert dialog title here
      	alert.setMessage("Digite ítem"); //Message here

          // Set an EditText view to get user input 
          final EditText input = new EditText(context);
          alert.setView(input);
         
      	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 = input.getEditableText().toString().toUpperCase();
          Cursor cursor = databaseHelper.getPutAwayItem(PONUMBER,srt);
 	     if(cursor.getCount()>0){
 	     cursor.moveToFirst();
 	     ID= cursor.getString(0);

 	     TextView qty = (TextView) findViewById(R.id.ofqty);
  	     qty.setText("de "+cursor.getString(4)+" "+cursor.getString(5));
 	     TextView conrev = (TextView) findViewById(R.id.conrev);
 	     conrev.setText("País"+"("+cursor.getString(11)+")");
 	    
	     TextView qtyreceived = (TextView) findViewById(R.id.already); 
	     qtyreceived.setText("Cantidad ya colocada: " +cursor.getString(13));
	     
	     TextView locused = (TextView) findViewById(R.id.localready); 
	     locused.setText("Posición(es) usada(s): " +cursor.getString(3));
	     
         //QTY=Double.parseDouble(cursor.getString(4));

	     QTYLOCATED=Double.parseDouble(cursor.getString(4))-Double.parseDouble(cursor.getString(13));
	    
   	     view.setText(cursor.getString(2));

     	 view.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
 	     COUNTER++;
 		 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  		 COUNTINGSTARTED = sd.format(new Date()); 
  		 

	    InvDatabaseHelper = new InventoryDatabaseHelper(context); 
	  	ListView listView = (ListView)findViewById(R.id.inventorylistviewinsideputaway);
	 	listView.setAdapter(null);
     
 	    StrictMode.setThreadPolicy(policy); 
 	    InvDatabaseHelper.deleteAllData();
 		try{
				
			String result = null;
	        InputStream is = null;
	      
	        String v1 = "'"+DATAAREAID+"'";
	    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
	    	String v2 = "'BOD_01'";
			String v3 = "'"+srt+"'"; 

	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
	        nameValuePairs.add(new BasicNameValuePair("UID",v3));
	        
	//apartir de aqui carga ruta
	 	
	  	try
	   	{
	        	        HttpClient httpclient = new DefaultHttpClient();
	        	        HttpPost httppost = new HttpPost("http://10.10.100.13/getLocationsRemaining.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");
	        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
	        	        }
	        	        is.close();
	        	        result=sb.toString();
	   	}
	   	catch(Exception e)
	   	{
	        	       Log.e("log_tag", "Error converting result "+e.toString());
	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
	   	}
	int COUNT=0;
	        	//parse json data
	        	try{

	        	 	JSONArray jArray = new JSONArray(result);
	        		for(int i=0;i<jArray.length();i++)  
		        {
	        			COUNT++;
	        			try{
	        		   	JSONObject no = jArray.getJSONObject(i);    
	        		    String loc=no.getString("Location");
	        		    String sku=no.getString("itemID");
	        	        String qty2=no.getString("qty");
	        		    try{
	        		    Double Qt = Double.parseDouble(qty2);
	        		    NumberFormat nf = NumberFormat.getInstance();
		 	            nf.setMaximumFractionDigits(0);// set as you need
		 	           qty2=nf.format(Qt).replace(",", "");
	        		    }catch(Exception e){}
	        		    
	        		    String type=no.getString("dim");
	        		   InvDatabaseHelper.saveInventoryLine(loc, sku, "", qty2, type, "","", "");
	 	            	}
	        	catch(JSONException e)
	        	{
	        	Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(COUNT));
	        	}
	        			
	        			   ViewGroup.LayoutParams params = listView.getLayoutParams();
	        		       
	        			if(COUNT==0){
	        				params.height = 67;
	        			}else{
	        				params.height =67*COUNT;}
	        			
	        	 		listView.setLayoutParams(params);
	        	 	    listView.requestLayout();
		        }}
	        	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.");
	        	}
 	
 	
 		 newInventoryAdapter = new InventoryAdapterSummary(context,InvDatabaseHelper.getInventoryItemLines(srt)); 			
    	 listView.setAdapter(newInventoryAdapter);

 	     }else{
 	     view.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
 	     Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  	     // Vibrate for 400 milliseconds
  	     v.vibrate(400);
 	     COUNTER=0;
 	     }
      	
      	    
      	} // End of onClick(DialogInterface dialog, int whichButton)
      }); //End of alert.setPositiveButton
      	alert.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
      	  public void onClick(DialogInterface dialog, int whichButton) {
      	    // Canceled.
      		  dialog.cancel();
      	  }
      }); //End of alert.setNegativeButton
      	AlertDialog alertDialog = alert.create();
      	alertDialog.show();
   
   }// End of onClick(View v)
});


		
		final TextView loc = (TextView) findViewById(R.id.location);	
		/* Se eliminar por ser inseguro digitacion manual
		loc.setOnClickListener(new View.OnClickListener() {
		      //When you click the button, Alert dialog will be showed
		      public void onClick(View v) {
		  
		      if(COUNTER==1){
		      	AlertDialog.Builder alert = new AlertDialog.Builder(context);
		      	alert.setTitle("Validación manual"); //Set Alert dialog title here
		      	alert.setMessage("Digite posición"); //Message here

		          // Set an EditText view to get user input 
		          final EditText input = new EditText(context);
		          alert.setView(input);
		         
		      	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 = input.getEditableText().toString().toUpperCase();
		      	if(COUNTER==1){
	           	    TextView buscarheader = (TextView) findViewById(R.id.location);
                  buscarheader.setText(srt);
                  LOCATION=srt;
            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
              	        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
                        myEditText.setClickable(true);
                        myEditText.setFocusable(true);
                        myEditText.setFocusableInTouchMode(true);
                        myEditText.requestFocus();
                        
            	    	try {
            	    	} catch (Exception e) {
            	    	    e.printStackTrace();
            	    	}
            	    COUNTER++;
                    		            	   
	               }	
		      	
		      	    
		      	} // End of onClick(DialogInterface dialog, int whichButton)
		      }); //End of alert.setPositiveButton
		      	alert.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
		      	  public void onClick(DialogInterface dialog, int whichButton) {
		      	    // Canceled.
		      		  dialog.cancel();
		      	  }
		      }); //End of alert.setNegativeButton
		      	AlertDialog alertDialog = alert.create();
		      	alertDialog.show();}
		
		   }// End of onClick(View v)
		});
*/
		
		GetData();
		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
	        switch (item.getItemId()) {
	            case R.id.add:
	            	if(execute==0){
		                Intent intent = new Intent(
		      	        "com.google.zxing.client.android.SCAN");
		      	        //intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
		      	        startActivityForResult(intent, 0);
		                return true;
		                
	            	}else{
			       		
		                	
		                	if(COUNTER==0){
			       		    TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
				    	     Cursor cursor = databaseHelper.getPutAwayItemBarcode(PONUMBER,Scanning);
				    	     if(cursor.getCount()>0){
				    	     cursor.moveToFirst();
				    	     
				    	     NOMBRESKU=cursor.getString(2);
				    	     ID= cursor.getString(0);
				    	     COUNTER++; 
				    		 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				    	     COUNTINGSTARTED = sd.format(new Date()); 	
				    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
				    	 	 buscarheader.setText(cursor.getString(2));
				     	
				    	     TextView qty = (TextView) findViewById(R.id.ofqty);
				    	     qty.setText("de "+cursor.getString(4)+" "+cursor.getString(5));
				    	     TextView conrev = (TextView) findViewById(R.id.conrev);
				    	 	    conrev.setText("País"+"("+cursor.getString(11)+")");
				    	     TextView qtyreceived = (TextView) findViewById(R.id.already); 
				    	     qtyreceived.setText("Cantidad ya colocada: " +cursor.getString(13));
				    	     
				    	     TextView locused = (TextView) findViewById(R.id.localready); 
				    	     locused.setText("Posición(es) usada(s): " +cursor.getString(3));
				    	     
				    	 	 QTYLOCATED=Double.parseDouble(cursor.getString(4))-Double.parseDouble(cursor.getString(13));
				    	     
				    	     InvDatabaseHelper = new InventoryDatabaseHelper(context); 
				    	  	ListView listView = (ListView)findViewById(R.id.inventorylistviewinsideputaway);
				    	 	listView.setAdapter(null);
				         
				     	    StrictMode.setThreadPolicy(policy); 
				     	    InvDatabaseHelper.deleteAllData();
				     		try{
				    				
				    			String result = null;
				    	        InputStream is = null;
				    	      
				    	        String v1 = "'"+DATAAREAID+"'";
				    	    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
				    	    	String v2 = "'BOD_01'";
				    			String v3 = "'"+NOMBRESKU+"'"; 

				    	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				    	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
				    	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
				    	        nameValuePairs.add(new BasicNameValuePair("UID",v3));
				    	        
				    	//apartir de aqui carga ruta
				    	 	
				    	  	try
				    	   	{
				    	        	        HttpClient httpclient = new DefaultHttpClient();
				    	        	        HttpPost httppost = new HttpPost("http://10.10.100.13/getLocationsRemaining.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");
				    	        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
				    	        	        }
				    	        	        is.close();
				    	        	        result=sb.toString();
				    	   	}
				    	   	catch(Exception e)
				    	   	{
				    	        	       Log.e("log_tag", "Error converting result "+e.toString());
				    	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
				    	   	}
				    	int counter=0;
				    	        	//parse json data
				    	        	try{

				    	        	 	JSONArray jArray = new JSONArray(result);
				    	        		for(int i=0;i<jArray.length();i++)  
				    		        {
				    	        			counter++;
				    	        			try{
				    	        		   	JSONObject no = jArray.getJSONObject(i);    
				    	        		    String loc=no.getString("Location");
				    	        		    String sku=no.getString("itemID");
				    	        	        String qty2=no.getString("qty");
				    	        		    try{
				    	        		    Double Qt = Double.parseDouble(qty2);
				    	        		    NumberFormat nf = NumberFormat.getInstance();
				    		 	            nf.setMaximumFractionDigits(0);// set as you need
				    		 	           qty2=nf.format(Qt).replace(",", "");
				    	        		    }catch(Exception e){}
				    	        		    
				    	        		    String type=no.getString("dim");
				    	        		   InvDatabaseHelper.saveInventoryLine(loc, sku, "", qty2, type, "","", "");
				    	 	            	}
				    	        	catch(JSONException e)
				    	        	{
				    	        	Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
				    	        	}
				    	        			
				    	        			   ViewGroup.LayoutParams params = listView.getLayoutParams();
				    	        		       
				    	        			if(counter==0){
				    	        				params.height = 67;
				    	        			}else{
				    	        				params.height =67*counter;}
				    	        			
				    	        	 		listView.setLayoutParams(params);
				    	        	 	    listView.requestLayout();
				    		        }}
				    	        	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.");
				    	        	}
				     		 newInventoryAdapter = new InventoryAdapterSummary(context,InvDatabaseHelper.getInventoryItemLines(NOMBRESKU)); 			
				        	 listView.setAdapter(newInventoryAdapter);	     
				    	     }
				    	     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){
			           	    TextView buscarheader = (TextView) this.findViewById(R.id.location);
                            buscarheader.setText(Scanning);
                            LOCATION=Scanning;
		            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
		              	        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
		                        myEditText.setClickable(true);
		                        myEditText.setFocusable(true);
		                        myEditText.setFocusableInTouchMode(true);
		                        myEditText.requestFocus();     
		            	    	try {
		            	    	} catch (Exception e) {
		            	    	    e.printStackTrace();
		            	    	}
		            	    COUNTER++;
	                        		            	   
			               }	 
			       			 
			       		Scanning="";
			       		execute=0;
			       			 
			       		 
		                }
		            case 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.getPutAwayItemBarcode(PONUMBER,Scanning);
					    	     if(cursor.getCount()>0){
					    	     cursor.moveToFirst();
					    	     
					    	     NOMBRESKU=cursor.getString(2);
					    	     ID= cursor.getString(0);
					    	     COUNTER++; 
					    		 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					    	     COUNTINGSTARTED = sd.format(new Date()); 	
					    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
					    	 	 buscarheader.setText(cursor.getString(2));
					     	
					    	     TextView qty = (TextView) findViewById(R.id.ofqty);
					    	     qty.setText("de "+cursor.getString(4)+" "+cursor.getString(5));
					    	     TextView conrev = (TextView) findViewById(R.id.conrev);
					    	 	    conrev.setText("País"+"("+cursor.getString(11)+")");
					    	     TextView qtyreceived = (TextView) findViewById(R.id.already); 
					    	     qtyreceived.setText("Cantidad ya colocada: " +cursor.getString(13));
					    	     
					    	     TextView locused = (TextView) findViewById(R.id.localready); 
					    	     locused.setText("Posición(es) usada(s): " +cursor.getString(3));
					    	     
					    	     
					    	     QTYLOCATED=Double.parseDouble(cursor.getString(4))-Double.parseDouble(cursor.getString(13));
					    	     
					    	     InvDatabaseHelper = new InventoryDatabaseHelper(context); 
					    	  	 ListView listView = (ListView)findViewById(R.id.inventorylistviewinsideputaway);
					    	 	listView.setAdapter(null);
					         
					     	    StrictMode.setThreadPolicy(policy); 
					     	    InvDatabaseHelper.deleteAllData();
					     		try{
					    				
					    			String result = null;
					    	        InputStream is = null;
					    	      
					    	        String v1 = "'"+DATAAREAID+"'";
					    	    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
					    	    	String v2 = "'BOD_01'";
					    			String v3 = "'"+NOMBRESKU+"'"; 

					    	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					    	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
					    	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
					    	        nameValuePairs.add(new BasicNameValuePair("UID",v3));
					    	        
					    	//apartir de aqui carga ruta
					    	 	
					    	  	try
					    	   	{
					    	        	        HttpClient httpclient = new DefaultHttpClient();
					    	        	        HttpPost httppost = new HttpPost("http://10.10.100.13/getLocationsRemaining.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");
					    	        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
					    	        	        }
					    	        	        is.close();
					    	        	        result=sb.toString();
					    	   	}
					    	   	catch(Exception e)
					    	   	{
					    	        	       Log.e("log_tag", "Error converting result "+e.toString());
					    	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
					    	   	}
					    	int counter=0;
					    	        	//parse json data
					    	        	try{

					    	        	 	JSONArray jArray = new JSONArray(result);
					    	        		for(int i=0;i<jArray.length();i++)  
					    		        {
					    	        			counter++;
					    	        			try{
					    	        		   	JSONObject no = jArray.getJSONObject(i);    
					    	        		    String loc=no.getString("Location");
					    	        		    String sku=no.getString("itemID");
					    	        	        String qty2=no.getString("qty");
					    	        		    try{
					    	        		    Double Qt = Double.parseDouble(qty2);
					    	        		    NumberFormat nf = NumberFormat.getInstance();
					    		 	            nf.setMaximumFractionDigits(0);// set as you need
					    		 	           qty2=nf.format(Qt).replace(",", "");
					    	        		    }catch(Exception e){}
					    	        		    
					    	        		    String type=no.getString("dim");
					    	        		   InvDatabaseHelper.saveInventoryLine(loc, sku, "", qty2, type, "","", "");
					    	 	            	}
					    	        	catch(JSONException e)
					    	        	{
					    	        	Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
					    	        	}
					    	        			
					    	        			   ViewGroup.LayoutParams params = listView.getLayoutParams();
					    	        		       
					    	        			if(counter==0){
					    	        				params.height = 67;
					    	        			}else{
					    	        				params.height =67*counter;}
					    	        			
					    	        	 		listView.setLayoutParams(params);
					    	        	 	    listView.requestLayout();
					    		        }}
					    	        	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.");
					    	        	}
					     	
					     	
					     		 newInventoryAdapter = new InventoryAdapterSummary(context,InvDatabaseHelper.getInventoryItemLines(NOMBRESKU)); 			
					        	 listView.setAdapter(newInventoryAdapter);
					        	
					      		 
					    	     
					    	     }
					    	     
					    	
					    	     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){
				           	    TextView buscarheader = (TextView) this.findViewById(R.id.location);
	                            buscarheader.setText(Scanning);
	                            LOCATION=Scanning;
			            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
			              	        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
			                        myEditText.setClickable(true);
			                        myEditText.setFocusable(true);
			                        myEditText.setFocusableInTouchMode(true);
			                        myEditText.requestFocus();     
			            	    	try {
			            	    	} catch (Exception e) {
			            	    	    e.printStackTrace();
			            	    	}
			            	    COUNTER++;
		                        		            	   
				               }	 
				       			 
				       		Scanning="";
				       		execute=0;
				       			 
				       		 
			                }
		            default:
	                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");
		               
		            
		               if(COUNTER==0){
		            	
		            	     TextView buscarheader = (TextView) this.findViewById(R.id.article);
		   		       	     buscarheader.setText(contents);
		   		    	     Cursor cursor = databaseHelper.getAllPutawayNonCompletedLines(PONUMBER,contents);
		   		    	     if(cursor.getCount()>0){
		   		    	     cursor.moveToFirst();
		   		    	     ID= cursor.getString(0);
		   		    	     SKU= cursor.getString(2);
		   		    	     TYPE= cursor.getString(5);
		   		    	     TextView loc=(TextView) this.findViewById(R.id.location);
		   		    	     loc.setText(cursor.getString(3));
		   		    	     
		   		    	     TextView qty = (TextView) this.findViewById(R.id.ofqty);
		   		    	     qty.setText("of "+cursor.getString(4)+" "+cursor.getString(5));
		   		    	     
		   		    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
		   		    	    // Cursor x =databaseHelper.getAllPutawayCompletedLines(cursor.getString(1), cursor.getString(2));
	                        QTYLOCATED=0;
	                        NumberFormat nf = NumberFormat.getInstance();
	                        nf.setMaximumFractionDigits(0);// set as you need
	                        QTY=Double.parseDouble(cursor.getString(4));
	                		//while (x.moveToNext()) {
	                	   // QTYLOCATED=QTYLOCATED+Double.parseDouble(x.getString(4));
	                		//}   
		   		    	     
		   		    	     COUNTER++;
		   		    	     }
		   		    	     
		   		    	     else{
		   		    	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));		 
		   		    	     }  
		               }
		               else if(COUNTER==1){
		            
		           	    TextView buscarheader = (TextView) this.findViewById(R.id.location);
		         
		           	    if(contents.equals(buscarheader.getText().toString().trim())){
		           	    	
		           	    LOCATION=buscarheader.getText().toString().trim();
		           	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
		           	    	
		           	    }else{
		           	    LOCATION= contents;
		           	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
		           	    buscarheader.setText(contents);
		           	    }
		           	    COUNTER++;

		               }

		                try{
		            	String[] casos = contents.split(";");
		            	String[] bodegayubicacion = casos[0].split(",");
		            	String[] bodegayempresa = bodegayubicacion[0].split(":");
		            	String posicion=bodegayubicacion[1];
		            	String bod=bodegayempresa[0];
		            	String empresa=bodegayempresa[1];}catch(Exception e){
		            	//Toast.makeText(getApplicationContext(), contents, Toast.LENGTH_SHORT).show(); }   
				    }
				    }

		 }}

      public void onComplete(View view) {  
				
		         if(COUNTER==0){
		       	Toast.makeText(getApplicationContext(), "Escanee o digite artículo para avanzar.", Toast.LENGTH_SHORT).show();
				   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
     			   intentemoslo.putExtra("voz","Escanee o digite artículo para avanzar");  
     			   startService(intentemoslo);	
		         }
		         if(COUNTER==1){
				       	Toast.makeText(getApplicationContext(), "Escanee o digite la ubicación para avanzar.", Toast.LENGTH_SHORT).show();	 
						   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			   intentemoslo.putExtra("voz","Escanee o digite la ubicación para avanzar");  
		     			   startService(intentemoslo);	 
		         }
		         EditText edittext = (EditText) this.findViewById(R.id.qtyamount);
		         if(COUNTER==2){  
		             Boolean TERMINUS=false;
		 		if(this.hasContent(edittext)==true&&this.hasContent(POSICION)){
		 		   double updateqty=Double.parseDouble(edittext.getText().toString().trim());
		 		   double totalstored=0;
		 		   String totallocation="";
		 	       NumberFormat nf = NumberFormat.getInstance();
                   nf.setMaximumFractionDigits(0);// set as you need
		 			if((updateqty)>QTYLOCATED){
			 	      	Toast.makeText(getApplicationContext(), "No puede ubicar una cantidad mayor a la existente.", Toast.LENGTH_SHORT).show();	 
						Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			intentemoslo.putExtra("voz","No puede ubicar una cantidad mayor a la existente.");  
		     			startService(intentemoslo);			 				
		 			}
		 			else{
		 				
		 				if((updateqty+QTYLOCATED)==QTY){
		 			    databaseHelper.UpdateScannedItem(ID);	
		 			  //  databaseHelper.savePutawayLine(PONUMBER, SKU, LOCATION, nf.format(updateqty), TYPE, "1", "1");
		 				}else{
		 			  //  databaseHelper.savePutawayLine(ponumber, sku, Location, qty, type, logtype, scanned, barcode, inventrans, inventdimid)(PONUMBER, SKU, LOCATION, nf.format(updateqty), TYPE, "1", "1");	
		 				}
		 				
		 				try{
			 				Cursor n = databaseHelper.getItemByID(ID);
			 				n.moveToFirst();
			 			 	String result = null;
			 			 	InputStream is = null;
				 			Spinner paises = (Spinner)findViewById(R.id.countries);
				 	        String paisrec = paises.getSelectedItem().toString();
			        		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				    		String dat = sd.format(new Date()); 
			 			 	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			 			  	nameValuePairs.add(new BasicNameValuePair("COUNTED","'"+updateqty+"'"));
			 			  	//SUBE ON HAND NO DIFERENCIA
			 			   TextView buscarheader = (TextView) findViewById(R.id.location);
	                        LOCATION= buscarheader.getText().toString();
			 			  	if(LOCATION.equals("")){
			 			  		TERMINUS=false;
			 			  	   Toast.makeText(getApplicationContext(), "Posición incorrecta; salga y vuelva a intentar.", Toast.LENGTH_SHORT).show();
			 			  	}
			 			  	
			 			 	nameValuePairs.add(new BasicNameValuePair("QTY","'"+n.getString(4)+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("EMP","'"+DATAAREAID+"'"));
			 			  	nameValuePairs.add(new BasicNameValuePair("LINE","'"+n.getString(10)+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("SKU","'"+n.getString(2)+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("DATE","'"+dat+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("BEGINDATE","'"+COUNTINGSTARTED+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("COUNTEDBY","'"+USERNAME+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("JID","'"+PONUMBER+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("ITRANS","'"+n.getString(9)+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("CONFIGID","'"+n.getString(5)+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("CONREC","'"+paisrec+"'"));
			 			    nameValuePairs.add(new BasicNameValuePair("LOCATION","'"+LOCATION+"'"));
			 			    totalstored=updateqty+Double.parseDouble(n.getString(13));
			 			    if(n.getString(3).equals(" ")){
			 			    totallocation=LOCATION;
			 			    }else{
			 			    totallocation= n.getString(3)+" - "+LOCATION;}
		 				   
			 			    
			 			    StrictMode.setThreadPolicy(policy); 
			 			    //http post
			 			    try{
			 			        	        HttpClient httpclient = new DefaultHttpClient();
			 			        	        HttpPost httppost = new HttpPost("http://10.10.100.13/UpdatePutAwayList.php");
			 			        	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			 			        	        HttpResponse response = httpclient.execute(httppost); 
			 			        	        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)
			 			        	{
			 			        	       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(Exception e)
			 			        	   {
			 			        	        Log.e("log_tag", "Error parsing data "+e.toString());
			 			        	     //   Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
			 			        	    }}catch(Exception e){}
			 					        	
			 					        
		 				if(TERMINUS){       
				 	      	Toast.makeText(getApplicationContext(), "Artículo registrado.", Toast.LENGTH_SHORT).show();	 
							Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
			     			intentemoslo.putExtra("voz","Artículo registrado");  
			     			try {
			    	     		
			     			} catch (Exception e) {
			     			    e.printStackTrace();
			     			}
			     			startService(intentemoslo);	
			     			edittext.setText("0");
			     			}
		     	
		 				if(TERMINUS){     	
		 					databaseHelper.UpdateReceivingItem(Double.toString(totalstored),totallocation,ID);
		 			 		 this.recreate();
		 		     			}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","Error de conexión. 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);
		 		     			}	  

		 			try{
						
						String result = null;
				    	InputStream is = null;
				  
				    	String v1 = "'"+DATAAREAID+"'";
						SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");


					
					String v3 = "'"+PONUMBER+"'"; 

				    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
				    	nameValuePairs.add(new BasicNameValuePair("UID",v3));
				    	
				//apartir de aqui carga ruta
					try
					{
				    	        HttpClient httpclient = new DefaultHttpClient();
				    	        HttpPost httppost = new HttpPost("http://10.10.100.13/getPutAwayNotProcessedList.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();
		                    String LINENUMOLD="";
		                    String ITRANSOLD="";
		                    String ITEMIDOLD="";
		                	double alreadycounted = 0; 	
		                	String COUNTQTY = ""; 	
		                	String LOCATION = "";
		                
				    	 	JSONArray jArray = new JSONArray(result);
				    		for(int i=0;i<jArray.length();i++)  
				            {
				    			try{
				    		   	JSONObject no = jArray.getJSONObject(i);

				    	        String COUNTED=no.getString("COUNTED");
				    	        String LINE=no.getString("LINENUM");
				    	        String WmsLocation=no.getString("WMSLOCATIONID");
				    
				    	        double receiveamount=0;
				    		    try{
				        		    Double Qt = Double.parseDouble(COUNTED);
				        		    receiveamount=Qt;
				        		    NumberFormat nf2 = NumberFormat.getInstance();
					 	            nf2.setMaximumFractionDigits(0);// set as you need
					 	        COUNTED=nf.format(Qt).replace(",", "");
				        		    
				        		}catch(Exception e){}

				      		    String itrans=no.getString("INVENTTRANSID");
				      		    String itemid=no.getString("ITEMID");
					            NumberFormat nf3 = NumberFormat.getInstance();
					            nf3.setMaximumFractionDigits(0);// set as you need
					        	Cursor xyz =databaseHelper.getItemDetail(PONUMBER,itrans,itemid,LINE);
					    		if(xyz.getCount()>0){
				
					    		xyz.moveToFirst();
					    		//wipe de lo que ya tiene es xyz;
					    	    databaseHelper.UpdateReceivingItem("0", " ", xyz.getString(0));
					    		if((LINENUMOLD.equals(LINE))&&(ITRANSOLD.equals(itrans))&&(ITEMIDOLD.equals(itemid))){
					    		alreadycounted=receiveamount+alreadycounted;	
					    		LOCATION=LOCATION+"-"+WmsLocation;
					    		}
					    		else{
					    	    alreadycounted=receiveamount;
					    	    LOCATION=WmsLocation;
					    	  
					    		}
					    	    COUNTQTY=nf.format(alreadycounted);
					    		LINENUMOLD=LINE;
					    		ITEMIDOLD=itemid;
					    		ITRANSOLD=itrans;
				                databaseHelper.UpdateReceivingItem(COUNTQTY, LOCATION, xyz.getString(0));
				                }
					            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.");
					}
		 		 this.recreate();
		 		 }
		 			
		 		}else{	
		
				       	Toast.makeText(getApplicationContext(), "Digite la cantidad y posición para avanzar.", Toast.LENGTH_SHORT).show();	 
						   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			   intentemoslo.putExtra("voz","Digite la cantidad para avanzar");  
		     			   startService(intentemoslo);	
		         }
		         }
				}	  
		    
	  private boolean hasContent(EditText et) {
			       return (et.getText().toString().trim().length() > 0);
			}
	  
	  private boolean hasContent(TextView et) {
	       return (et.getText().toString().trim().length() > 0);
	}
	  
	  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();
		      //
		    }
		    // let the default implementation handle the event

		    new CountDownTimer(1000, 1000) {       
				   public void onTick(long millisUntilFinished) {          
				}       

				public void onFinish() {   
					if(execute==1){
					execute=0;
					if(COUNTER==0){
		       		    TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
			    	     Cursor cursor = databaseHelper.getPutAwayItemBarcode(PONUMBER,Scanning);
			    	     if(cursor.getCount()>0){
			    	     cursor.moveToFirst();
			    	     ID= cursor.getString(0);
			    	     COUNTER++; 
			    		 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			    	     COUNTINGSTARTED = sd.format(new Date()); 	
			    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));	

			    	     InvDatabaseHelper = new InventoryDatabaseHelper(context); 
			    	  	ListView listView = (ListView)findViewById(R.id.inventorylistviewinsideputaway);
			    	 	listView.setAdapter(null);
			         
			     	    StrictMode.setThreadPolicy(policy); 
			     	    InvDatabaseHelper.deleteAllData();
			     		try{
			    				
			    			String result = null;
			    	        InputStream is = null;
			    	      
			    	        String v1 = "'"+DATAAREAID+"'";
			    	    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
			    	    	String v2 = "'BOD_01'";
			    			String v3 = "'"+Scanning+"'"; 

			    	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			    	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
			    	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
			    	        nameValuePairs.add(new BasicNameValuePair("UID",v3));
			    	        
			    	//apartir de aqui carga ruta
			    	 	
			    	  	try
			    	   	{
			    	        	        HttpClient httpclient = new DefaultHttpClient();
			    	        	        HttpPost httppost = new HttpPost("http://10.10.100.13/getLocationsRemaining.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");
			    	        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
			    	        	        }
			    	        	        is.close();
			    	        	        result=sb.toString();
			    	   	}
			    	   	catch(Exception e)
			    	   	{
			    	        	       Log.e("log_tag", "Error converting result "+e.toString());
			    	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
			    	   	}
			    	int counter=0;
			    	        	//parse json data
			    	        	try{

			    	        	 	JSONArray jArray = new JSONArray(result);
			    	        		for(int i=0;i<jArray.length();i++)  
			    		        {
			    	        			counter++;
			    	        			try{
			    	        		   	JSONObject no = jArray.getJSONObject(i);    
			    	        		    String loc=no.getString("Location");
			    	        		    String sku=no.getString("itemID");
			    	        	        String qty2=no.getString("qty");
			    	        		    try{
			    	        		    Double Qt = Double.parseDouble(qty2);
			    	        		    NumberFormat nf = NumberFormat.getInstance();
			    		 	            nf.setMaximumFractionDigits(0);// set as you need
			    		 	           qty2=nf.format(Qt).replace(",", "");
			    	        		    }catch(Exception e){}
			    	        		    
			    	        		    String type=no.getString("dim");
			    	        		   InvDatabaseHelper.saveInventoryLine(loc, sku, "", qty2, type, "","", "");
			    	 	            	}
			    	        	catch(JSONException e)
			    	        	{
			    	        	Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
			    	        	}
			    	        			
			    	        			   ViewGroup.LayoutParams params = listView.getLayoutParams();
			    	        		       
			    	        			if(counter==0){
			    	        			params.height = 67;
			    	        			}else{
			    	        			params.height =67*counter;}
			    	        			
			    	        			
			    	        	 		listView.setLayoutParams(params);
			    	        	 	    listView.requestLayout();
			    		        }}
			    	        	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.");
			    	        	}
			     	
			     	
			     		 newInventoryAdapter = new InventoryAdapterSummary(context,InvDatabaseHelper.getInventoryItemLines(Scanning)); 			
			        	 listView.setAdapter(newInventoryAdapter);
			        	
			      		 
			    	     
			    	     }
			    	     
			    	
			    	     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){
		           	    TextView buscarheader = (TextView) findViewById(R.id.location);
                        buscarheader.setText(Scanning);
	            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
	              	        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
	                        myEditText.setClickable(true);
	                        myEditText.setFocusable(true);
	                        myEditText.setFocusableInTouchMode(true);
	                        myEditText.requestFocus();     
	            	    	try {
	            	    	} catch (Exception e) {
	            	    	    e.printStackTrace();
	            	    	}
	            	    COUNTER++;
                        		            	   
		               }

		      	      Scanning="";
					}
				
				}
				   
				}.start();  
	        
	        return super.onKeyDown(keyCode, event);
		}

		private void GetData() {

		//Receive data from bluetooth scanner

			UsbConnect.SetOnDataReceive(new OnDataReceive() {
				@Override
				public void DataReceive(byte[] data , boolean flg) {
				    Scanning=Scanning+new String(data).trim();
					  if(timerstarted==0&&(Scanning.equals("")==false)){
						  timerstarted=1;
					 	new CountDownTimer(300, 300) {       
							   public void onTick(long millisUntilFinished) {          
							}       
							public void onFinish() {  timercompleted=true; 	
							if(timercompleted==true){	
				  if(Scanning.equals("")){}
				  else{
					  if(COUNTER==0){
			       		    TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
				    	     Cursor cursor = databaseHelper.getPutAwayItemBarcode(PONUMBER,Scanning);
				    	     if(cursor.getCount()>0){
				    	     cursor.moveToFirst();
				    	     ID= cursor.getString(0);
				    	     COUNTER++; 
				    		 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				    	     COUNTINGSTARTED = sd.format(new Date()); 	
				    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));	
				    	     

				    	    InvDatabaseHelper = new InventoryDatabaseHelper(context); 
				    	  	ListView listView = (ListView)findViewById(R.id.inventorylistviewinsideputaway);
				    	 	listView.setAdapter(null);
				         
				     	    StrictMode.setThreadPolicy(policy); 
				     	   InvDatabaseHelper.deleteAllData();
				     		try{
				    				
				    			String result = null;
				    	        InputStream is = null;
				    	      
				    	        String v1 = "'"+DATAAREAID+"'";
				    	    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
				    	    	String v2 = "'BOD_01'";
				    			String v3 = "'"+Scanning+"'"; 

				    	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				    	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
				    	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
				    	        nameValuePairs.add(new BasicNameValuePair("UID",v3));
				    	        
				    	//apartir de aqui carga ruta
				    	 	
				    	  	try
				    	   	{
				    	        	        HttpClient httpclient = new DefaultHttpClient();
				    	        	        HttpPost httppost = new HttpPost("http://10.10.100.13/getLocationsRemaining.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");
				    	        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
				    	        	        }
				    	        	        is.close();
				    	        	        result=sb.toString();
				    	   	}
				    	   	catch(Exception e)
				    	   	{
				    	        	       Log.e("log_tag", "Error converting result "+e.toString());
				    	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
				    	   	}
				    	int counter=0;
				    	        	//parse json data
				    	        	try{

				    	        	 	JSONArray jArray = new JSONArray(result);
				    	        		for(int i=0;i<jArray.length();i++)  
				    		        {
				    	        			counter++;
				    	        			try{
				    	        		   	JSONObject no = jArray.getJSONObject(i);    
				    	        		    String loc=no.getString("Location");
				    	        		    String sku=no.getString("itemID");
				    	        	        String qty2=no.getString("qty");
				    	        		    try{
				    	        		    Double Qt = Double.parseDouble(qty2);
				    	        		    NumberFormat nf = NumberFormat.getInstance();
				    		 	            nf.setMaximumFractionDigits(0);// set as you need
				    		 	           qty2=nf.format(Qt).replace(",", "");
				    	        		    }catch(Exception e){}
				    	        		    
				    	        		    String type=no.getString("dim");
				    	        		   InvDatabaseHelper.saveInventoryLine(loc, sku, "", qty2, type, "","", "");
				    	 	            	}
				    	        	catch(JSONException e)
				    	        	{
				    	        	Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
				    	        	}
				    	        			
				    	        			   ViewGroup.LayoutParams params = listView.getLayoutParams();
				    	        		       
				    	        			if(counter==0){
				    	        				params.height = 67;
				    	        			}else{
				    	        				params.height =67*counter;}
				    	        			
				    	        	 		listView.setLayoutParams(params);
				    	        	 	    listView.requestLayout();
				    		        }}
				    	        	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.");
				    	        	}
				     	
				     	
				     		 newInventoryAdapter = new InventoryAdapterSummary(context,InvDatabaseHelper.getInventoryItemLines(Scanning)); 			
				        	 listView.setAdapter(newInventoryAdapter);

				    	     }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){
			           	    TextView buscarheader = (TextView) findViewById(R.id.location);
                          buscarheader.setText(Scanning);
                          LOCATION=Scanning;
		            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
		              	        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
		                        myEditText.setClickable(true);
		                        myEditText.setFocusable(true);
		                        myEditText.setFocusableInTouchMode(true);
		                        myEditText.requestFocus();
		                        
		            	    	try {
		            	    	} catch (Exception e) {
		            	    	    e.printStackTrace();
		            	    	}
		            	    COUNTER++;
	                        		            	   
			               }		 
			       			 
			       		Scanning="";
			       		execute=0;

				  }
                  timerstarted=0;
	      	      Scanning="";
	      	      timercompleted=false;
			  }

		}}.start();  
		}
	
		}


		});

		}

}
