package com.example.waoperations.Picking;


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.VoiceHelper;
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.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.StrictMode;
import android.os.Vibrator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class PickingDetail 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,EXISTENTE,LOC,SKU,DATAAREAID,OFQTY,COUNTINGSTARTED,USERNAME,ORDERID,ROUTEID,INVENTDIMID,INVENTRANS,USEBARCODE;
	  public String qtyautorizada;
      public TextView POSICION,ARTICULO,CANTIDAD;
      public EditText ED;
	  final Context context = this;
	  public String ID;
      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)");
	  PickingAdapter newPickingAdapter;
	  private PickingDatabaseHelper databaseHelper;
	  
protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
		setContentView(R.layout.wapickingitem);
		databaseHelper = new PickingDatabaseHelper(this.getApplicationContext()); 
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    actionBar.setSubtitle("Picking");
	    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");
        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);
	     
	     if(EXISTENTE.equals("0")){
	    	 try{
	     Cursor cursor = databaseHelper.getNonScannedItemsPerPO(PONUMBER);
	     cursor.moveToFirst();
	     ID= cursor.getString(0);
	
	     
	     TextView position = (TextView) this.findViewById(R.id.buscarheader);
	     TextView sku = (TextView) this.findViewById(R.id.article);
	     TextView qty = (TextView) this.findViewById(R.id.ofqty);
	     position.setText(cursor.getString(2));
	     sku.setText(cursor.getString(3));
	     qty.setText("de "+cursor.getString(5)+" "+cursor.getString(6));
	 
	     qtyautorizada=cursor.getString(5);
		    
	 	if(cursor.getString(15).equals("1")){
	 		AlertDialog.Builder alert = new AlertDialog.Builder(context);
        	alert.setTitle("Picking"); //Set Alert dialog title here
        	alert.setMessage("REABASTECIMIENTO PENDIENTE EN ESTA ZONA NO PUEDE AVANZAR."); //Message here
            // Set an EditText view to get user 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.
       	 finish(); 
   
        	} // End of onClick(DialogInterface dialog, int whichButton)

        }); //End of alert.setNegativeButton
        	AlertDialog alertDialog = alert.create();
        	alertDialog.show();
   
	 	}
	     
	        edittext.setText(cursor.getString(5));

	        edittext.setClickable(false);
	        edittext.setFocusable(false);
	     TextView country = (TextView) this.findViewById(R.id.countrypick);
	     country.setText("País:"+cursor.getString(10));
	     }catch(Exception e){ 
	     Toast toasta=Toast.makeText(getApplicationContext(), "No hay más productos por alistar.", 2000);
	     this.finish();
	     }
	     } else{
		 		this.INVENTDIMID = intent.getStringExtra("INVENDIMID");
			
			     Cursor cursor = databaseHelper.getItemByID(INVENTDIMID);
			     cursor.moveToFirst();
			     ID= cursor.getString(0);
			     
			     
			     
			     TextView position = (TextView) this.findViewById(R.id.buscarheader);
			     TextView sku = (TextView) this.findViewById(R.id.article);
			     TextView qty = (TextView) this.findViewById(R.id.ofqty);
			     position.setText(cursor.getString(2));
			     sku.setText(cursor.getString(3));
			     qty.setText("de "+cursor.getString(5)+" "+cursor.getString(6));
			     qtyautorizada=cursor.getString(5);
			     
				 	if(cursor.getString(15).equals("1")){
				 		AlertDialog.Builder alert = new AlertDialog.Builder(context);
			        	alert.setTitle("Picking"); //Set Alert dialog title here
			        	alert.setMessage("REABASTECIMIENTO PENDIENTE EN ESTA ZONA NO PUEDE AVANZAR."); //Message here
			 
			            // Set an EditText view to get user 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.
			      
			        
			       	 finish(); 
			   
			        	    
			        	} // End of onClick(DialogInterface dialog, int whichButton)

			        }); //End of alert.setNegativeButton
			        	AlertDialog alertDialog = alert.create();
			        	alertDialog.show();
	
				 	}
			     
			     
			        edittext.setText(cursor.getString(5));
			        edittext.setClickable(false);
			        edittext.setFocusable(false);
			     TextView country = (TextView) this.findViewById(R.id.countrypick);
			     country.setText("País:"+cursor.getString(10));
		     }  
		     
		final TextView view = (TextView) findViewById(R.id.article);
			
			view.setOnClickListener(new View.OnClickListener() {
	        //When you click the button, Alert dialog will be showed
	        public void onClick(View v) {
	       /* Alert Dialog Code Start*/ 	
	        	  if(COUNTER==1){
	        	AlertDialog.Builder alert = new AlertDialog.Builder(context);
	        	alert.setTitle("Validación de sku"); //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();
	            TextView PO = (TextView)findViewById(R.id.article);  
	            
	        	if(srt.equals(PO.getText().toString().toUpperCase())){
	        		    USEBARCODE="0";
	        	    	PO.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++;
	                }else{
	        	    	PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
	        	      	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                	// Vibrate for 400 milliseconds
	                	v.vibrate(400);
	        	    }
	        	    
	        	} // 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();
	        	  }
	        }); //End of alert.setNegativeButton
	        	AlertDialog alertDialog = alert.create();
	        	alertDialog.show();
	       /* Alert Dialog Code End*/        
	     }// End of onClick(View v)
	  }});
		     
		          			
			
			
	}

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) this.findViewById(R.id.buscarheader);
		            	    if(Scanning.equals(buscarheader.getText())){
		            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
		            	    	try {
		            
		            	    	} catch (Exception e) {
		            	    	    e.printStackTrace();
		            	    	}
		            	    COUNTER++;
                            }else{
                            	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                            	// Vibrate for 400 milliseconds
                            	v.vibrate(400);
		            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
		            	    } 
		               }
		               else if(COUNTER==1){
		           	    TextView buscarheader = (TextView) this.findViewById(R.id.article);
		                Cursor cursor = databaseHelper.getCountItemBarcode(PONUMBER, Scanning);
		                if(cursor.getCount()>0){
		                cursor.moveToFirst();
		                
		           	    if(cursor.getString(3).equals(buscarheader.getText())){
		           	        USEBARCODE="1";
	            	    	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++;
                        }}else{
                        	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                        	// Vibrate for 400 milliseconds
                        	v.vibrate(400);
	            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
	            	    } 		            	   
		               }	 
		       			 
		       		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) this.findViewById(R.id.buscarheader);
			            	    if(Scanning.equals(buscarheader.getText())){
			            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
			            	    	try {
			            	    	} catch (Exception e) {
			            	    	    e.printStackTrace();
			            	    	}
			            	    COUNTER++;
	                            }else{
	                            	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                            	// Vibrate for 400 milliseconds
	                            	v.vibrate(400);
			            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
			            	    } 
			               }
			               else if(COUNTER==1){
			           	    TextView buscarheader = (TextView) this.findViewById(R.id.article);
			                Cursor cursor = databaseHelper.getCountItemBarcode(PONUMBER, Scanning);
			                if(cursor.getCount()>0){
			                cursor.moveToFirst();
			                
			           	    if(cursor.getString(3).equals(buscarheader.getText())){
			           	        USEBARCODE="1";
		            	    	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++;
	                        }}else{
	                        	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                        	// Vibrate for 400 milliseconds
	                        	v.vibrate(400);
		            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
		            	    } 		            	   
			               }	 
			       			 
			       		Scanning="";
			       		execute=0;
			       			 
	            		
	            	 }
	            default:
	                return super.onOptionsItemSelected(item);
	        }
	    }
	    
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.buscarheader);
		            	    if(contents.equals(buscarheader.getText())){
		            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
		            	    COUNTER++;
                            }else{
		            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
		            	    	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                    	// Vibrate for 400 milliseconds
		                    	v.vibrate(400);
                            }
		               }
		               else if(COUNTER==1){
		           	    TextView buscarheader = (TextView) this.findViewById(R.id.article);
                        Cursor cursor = databaseHelper.getPickingItemBarcode(PONUMBER,contents);
                        if(cursor.getCount()>0){
		           	    cursor.moveToFirst();
	            	    if(cursor.getString(3).equals(buscarheader.getText())){
	            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
	            	    COUNTER++;
                        }
                        }else{
	            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
	            	    	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                    	// Vibrate for 400 milliseconds
	                    	v.vibrate(400);
	            	    
	            	    }   
		               }

				    }
		 }}

public void onComplete(View view) {  
		         if(COUNTER==0){
		       	 Toast.makeText(getApplicationContext(), "Verifique la posición para avanzar.", Toast.LENGTH_SHORT).show();
				   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
     			   intentemoslo.putExtra("voz","Verifique la posición para avanzar");  
     			   startService(intentemoslo);	
     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                	// Vibrate for 400 milliseconds
                	v.vibrate(400);
		         }
		         if(COUNTER==1){
		        
				       	Toast.makeText(getApplicationContext(), "Verifique el artículo para avanzar.", Toast.LENGTH_SHORT).show();	 
						   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			   intentemoslo.putExtra("voz","Verifique el artículo para avanzar");  
		     			   startService(intentemoslo);	
		     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                	v.vibrate(400);    
		         }
		         EditText edittext = (EditText) this.findViewById(R.id.qtyamount);
		         
		         if(COUNTER==2){
                Boolean TERMINUS=false;
                //Condicion que valida si el campo de contado fue digitado, sino alerta al usuario para que lo rellene.
		 		if(this.hasContent(edittext)==true){
		 			
		 			String qtypicked = edittext.getText().toString();
		 			double qtyautorizadaf= Double.parseDouble(qtyautorizada);
		 			double qtypickedf = Double.parseDouble(qtypicked);
		 			
		 			  //Condicion que valida si la cantidad digitada es menor o igual a la autorizada, en caso contrario alerta al usuario para que revise la cantidad.
		 			if(qtypickedf<=qtyautorizadaf){

		 			databaseHelper.UpdateScannedItem(edittext.getText().toString().trim(),ID);
		 			
		 			try{
		 				Cursor n = databaseHelper.getItemByID(ID);
		 				n.moveToFirst();
		 			 	String result = null;
		 			 	InputStream is = null;
		 			 	
		                Double diferencia=Double.parseDouble(n.getString(7))-Double.parseDouble(n.getString(5));
		                NumberFormat nf = NumberFormat.getInstance();
		                nf.setMaximumFractionDigits(0);// set as you need
		        		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("COUNT","'"+n.getString(7)+"'"));
		 			  	//SUBE ON HAND NO DIFERENCIA
		 			 	nameValuePairs.add(new BasicNameValuePair("IOH","'"+n.getString(5)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("EMP","'"+DATAAREAID+"'"));
		 			  	nameValuePairs.add(new BasicNameValuePair("LINE","'"+n.getString(14)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("SKU","'"+n.getString(3)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("DATE","'"+dat+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("BEGINDATE","'"+COUNTINGSTARTED+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("USER","'"+USERNAME+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("PO","'"+PONUMBER+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("ORDERID","'"+n.getString(11)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("ROUTEID","'"+n.getString(12)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("INVENTRANS","'"+n.getString(13)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("WMSLOCATIONID","'"+n.getString(2)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("SCANNED","'"+USEBARCODE+"'"));
		 			    StrictMode.setThreadPolicy(policy); 
		 			    
		 			    //http post
		 			    try{
		 			        	        HttpClient httpclient = new DefaultHttpClient();
		 			        	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/UpdatePickingList2.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);	
	     		
	     			}
	     			
	     		
	     			
	     			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://200.91.85.150/WAOPSPHP/Picking/getPickingNotProcessedList.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("COUNTED");
	     		    	        String orderid=no.getString("ORDERID");
	     		    
	     		    	        double receiveamount=0;
	     		    		    try{
	     		        		    Double Qt = Double.parseDouble(COUNTED);
	     		        		    receiveamount=Qt;
	     		        		    NumberFormat nf = NumberFormat.getInstance();
	     			 	            nf.setMaximumFractionDigits(0);// set as you need
	     			 	        COUNTED=nf.format(Qt).replace(",", "");
	     		        		    
	     		        		}catch(Exception e){}
	     		      		    String itrans=no.getString("INVENTDIMID");
	     		      		    String itemid=no.getString("ITEMID");
	     			            NumberFormat nf = NumberFormat.getInstance();
	     			            nf.setMaximumFractionDigits(0);// set as you need
	     			        	Cursor xyz =databaseHelper.getItemDetail(PONUMBER,itrans,itemid,orderid);
	     			    		if(xyz.getCount()>0){
	     			    		xyz.moveToFirst();
	     		                databaseHelper.UpdateScannedItem(COUNTED, 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.");
	     			}
	     			
	     			if(TERMINUS){     
	     			  if(EXISTENTE.equals("0")){
	     			  this.recreate();		  
	     			  }else{
	     				 finish(); 
	     			  }
	     			  }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);
	     			  }
		 		
		 		}else{
		 		 	Toast.makeText(getApplicationContext(), "La cantidad no puede superar lo permitido.", Toast.LENGTH_SHORT).show();	 
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","La cantidad no puede superar lo permitido.");  
	     			   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);
			}
	  
    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

    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);
	    if(Scanning.equals(buscarheader.getText())){
	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
	    	
	    	try {
	    	} catch (Exception e) {
	    	    e.printStackTrace();
	    	}
	    COUNTER++;
        }else{
        	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        	// Vibrate for 400 milliseconds
        	v.vibrate(400);
	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
	    } 
   }
   else if(COUNTER==1){
	    TextView buscarheader = (TextView) findViewById(R.id.article);
	    Cursor cursor = databaseHelper.getPickingItemBarcode(PONUMBER,Scanning);
        if(cursor.getCount()>0){
        cursor.moveToFirst();

	    if(cursor.getString(3).equals(buscarheader.getText())){
    	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++;
    }}else{
    	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    	// Vibrate for 400 milliseconds
    	v.vibrate(400);
    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
     } 		            	   
     }	 
  }
  timerstarted=0;
    Scanning="";
    timercompleted=false;
}




}}.start();  
}
}


});

}

}


