package com.example.waoperations.CycleCount;




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.Inventory.InventoryAdapter;
import com.example.waoperations.Inventory.InventoryDatabaseHelper;
import com.example.waoperations.Picking.PickingAdapter;
import com.example.waoperations.Picking.PickingDatabaseHelper;
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.ActivityNotFoundException;
import android.content.ComponentName;
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.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
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.Gravity;
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 CycleCountDetailProgrammed extends Activity {
	  private static final int REQUEST_CODE = 1234;
	  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	  private static final String CALCULATOR_PACKAGE_NAME = "com.android.calculator2";    
   	  private static final String CALCULATOR_CLASS_NAME = "com.android.calculator2.Calculator";
	  public int COUNTER =0;
	  public String PONUMBER,EXISTENTE,LOC,SKU,DATAAREAID,OFQTY,COUNTINGSTARTED,USERNAME,DIGITADO,BARCODE,COUNTID;
	  private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
	  public String Scanning="";
      public TextView POSICION,ARTICULO,CANTIDAD;
      public EditText ED;
      public int execute=0;
      public int timerstarted=0;
      public Boolean timercompleted=false;
	  public String ID;
	  CycleCountAdapter newCycleCountAdapter;
	  final Context context = this;
	  private CycleCountDatabaseHelper databaseHelper;
      private InventoryDatabaseHelper InvDatabaseHelper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
		setContentView(R.layout.wacyclecountitem);
		databaseHelper = new CycleCountDatabaseHelper(this.getApplicationContext()); 
	    ActionBar actionBar = getActionBar();
	    actionBar.hide(); 
	    // more stuff here...
	    actionBar.setSubtitle("Cycle count");
	    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(); 
		InvDatabaseHelper = new InventoryDatabaseHelper(this.getApplicationContext()); 
		InvDatabaseHelper.deleteAllData();
		Intent intent = getIntent();
		this.PONUMBER = intent.getStringExtra("PO");
	
		this.DATAAREAID = intent.getStringExtra("DATA");
		this.USERNAME = intent.getStringExtra("USER");
		
		
		this.LOC=intent.getStringExtra("LOC");
		this.SKU=intent.getStringExtra("SKU");
		this.COUNTID=intent.getStringExtra("COUNTID");
		
		
		
		
		TextView position = (TextView) this.findViewById(R.id.buscarheader);
	    position.setText(this.PONUMBER);
	    
	    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);
	     POSICION.setText(LOC.trim());
	     ARTICULO = (TextView) this.findViewById(R.id.article);
	     ARTICULO.setText(SKU.trim());
	     CANTIDAD = (TextView) this.findViewById(R.id.ofqty);
	     
	     Cursor cursor = databaseHelper.getCCItem(LOC,SKU);
 	     if(cursor.getCount()>0){
 	     cursor.moveToFirst();
 	     ID= cursor.getString(0);
 	      TextView qty = (TextView) findViewById(R.id.ofqty);
    	     
	      
	            qty.setText("de "+cursor.getString(5)+" "+cursor.getString(6));

                TextView cont = (TextView) findViewById(R.id.countryname);
         	    cont.setText("País: "+cursor.getString(12));
         	    
            //myEditText.requestFocus();
	    	try {

	    	} catch (Exception e) {
	    	    e.printStackTrace();
	    	}
 	     }
	     
	     ED = (EditText) this.findViewById(R.id.qtyamount);

		 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"};
   		 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);

   	String[] conf = new String[]{"und","B6","B10","B11","B12","B2","B250","B3","B4","B48","B5","B7","B8","B9","DR","PL"};
  	Spinner equipment2 = (Spinner) findViewById(R.id.configuracion);
  	ArrayAdapter adapter3 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, conf);
  	
  	// Specify the layout to use when the list of choices appears
  	adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  	// Apply the adapter to the spinner
  	equipment2.setAdapter(adapter3);
	     
	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 ítem"); //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();
        	 DIGITADO=srt;
        		TextView PO = (TextView)findViewById(R.id.article);
        		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();
                
        	 
        	    COUNTER++;
                
        	    
        	} // 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)
  }});
 
		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");
		      	        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);
		                BARCODE=Scanning;
		                if(cursor.getCount()>0){
		                cursor.moveToFirst();
		       	        ID= cursor.getString(0);

	            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
	            	    	buscarheader.setText(cursor.getString(3));
	            	        TextView qty = (TextView) this.findViewById(R.id.ofqty);
	            		    qty.setText("de "+cursor.getString(5)+" "+cursor.getString(6));
					     	     
						    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{} 		            	   
		               }	 
		       			 
		       		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);
			                BARCODE=Scanning;
			                if(cursor.getCount()>0){
			                cursor.moveToFirst();

			       	     ID= cursor.getString(0);
			         	   
		            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
		            	    	buscarheader.setText(cursor.getString(3));
		            	        TextView qty = (TextView) this.findViewById(R.id.ofqty);
		            		    qty.setText("de "+cursor.getString(5)+" "+cursor.getString(6));
						     	     
							    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{


			                    
			                	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
			        	      	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			                	// Vibrate for 400 milliseconds
			                	v.vibrate(400);

			                	AlertDialog.Builder alert = new AlertDialog.Builder(context);
			                	alert.setTitle("ítem no encontrado"); //Set Alert dialog title here
			                	alert.setMessage("Este ítem no debería encontrarse en esta ubicación. Desea agregarlo?"); //Message here
			         
			                    // Set an EditText view to get user input 
			                   
			                   
			                	alert.setPositiveButton("Sí", 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.
			                	
			                		TextView PO = (TextView)findViewById(R.id.article);
			                		String INVENTDIMID ="NA";
			                		String COUNTRY ="";
			               	     

			               	      InvDatabaseHelper = new InventoryDatabaseHelper(context); 
			              	  
			                  
			              	    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 = "'"+BARCODE+"'"; 

			              	        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/getLocationsRemainingBarcodeInv.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");
			              	        		    DIGITADO=sku;
			              	        		  
			              	        	        String qty2=no.getString("qty");
			              	        	        String inventserial = no.getString("invdim");
			              	        	        String config =no.getString("country");
			              	        	        INVENTDIMID=inventserial;
			              	        	        COUNTRY=config;
			              	        		    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));
			              	        	}
			        
			              		        }}
			              	        	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(INVENTDIMID=="NA"){
			          	        	Toast.makeText(getApplicationContext(), "Artículo no existente.", Toast.LENGTH_SHORT).show();

			                   	  	}else{  
			               	         //ACÃ� TENGO QUE AGREGARLE EL INVENTDIMID E INSERTARLO EN LA BASE DE DATOS
			               	  	databaseHelper.saveCycleCountLine(PONUMBER,PONUMBER,DIGITADO,"-","0",COUNTRY,"0","0",BARCODE,INVENTDIMID,"0","");

			               	  	
			               	    Cursor cursor = databaseHelper.getCCItem(PONUMBER,DIGITADO);
			            	       if(cursor.getCount()>0){
			            	       cursor.moveToFirst();
			            	       ID= cursor.getString(0);
			          	           TextView qty = (TextView) findViewById(R.id.ofqty);
			          	           PO.setText(cursor.getString(3));
			          	           qty.setText("de 0 und");
			           	    	   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();
			                       //myEditText.requestFocus();
			           	    	try {
			           
			           	    	} catch (Exception e) {
			           	    	    e.printStackTrace();
			           	    	}
			           	    COUNTER++;
			               	  	
			            	     }}
			                	} // End of onClick(DialogInterface dialog, int whichButton)
			                }); //End of alert.setPositiveButton
			                	alert.setNegativeButton("No", 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*/        
			             
			        	    
			        	    
			        	    
			        	     } 		            	   
			               }	 
			       			 
			       		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.buscarheader);
		            	    if(contents.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, contents);
		                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.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)));	
	            	    } 		            	   
		               }
		                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(), "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");  
     			 Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                 // Vibrate for 400 milliseconds
                 v.vibrate(400);
     			 startService(intentemoslo);	
		         }
		         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");  
		     	 Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                 // Vibrate for 400 milliseconds
                 v.vibrate(400);
		     	 startService(intentemoslo);	 
		         }

		         EditText edittext = (EditText) this.findViewById(R.id.qtyamount);
		         if(COUNTER==2){
		             Boolean TERMINUS=false;
		 		if(this.hasContent(edittext)==true){
		 			
		 			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(10)+"'"));
		 			    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("WMSLOCATIONID","'"+LOC+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("COUNTRYOR","'"+n.getString(12)+"'"));
		 			    
		 				Spinner paises = (Spinner)findViewById(R.id.countries);
			 	        String paisrec = paises.getSelectedItem().toString();
		 			    nameValuePairs.add(new BasicNameValuePair("COUNTRYREC","'"+paisrec+"'"));
		 			    
		 				Spinner type = (Spinner) findViewById(R.id.configuracion);
			 	        String TYPE = type.getSelectedItem().toString();
		 			    nameValuePairs.add(new BasicNameValuePair("TYPE","'"+TYPE+"'"));
		 			   nameValuePairs.add(new BasicNameValuePair("COUNTID","'"+COUNTID+"'"));
		 			    StrictMode.setThreadPolicy(policy); 
		 			        	//http post
		 			        	try{
		 			        	        HttpClient httpclient = new DefaultHttpClient();
		 			        	        HttpPost httppost = new HttpPost("http://10.10.100.13/UpdateCycleCountProgrammedList.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(JSONException e)
		 			        	   {
		 			        	        Log.e("log_tag", "Error parsing data "+e.toString());
		 			        	     //   Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
		 			        	    }}catch(Exception e){}

		 			if(TERMINUS){       
			 	      	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("");
		     			 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(), "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);	
		         }
		         }
				}	  
		    
		private boolean hasContent(EditText et) {
			       return (et.getText().toString().trim().length() > 0);
			}
		
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
				
			    	execute=1;
			    	
			        String key = KeyEvent.keyCodeToString(keyCode);
			        
			        // key will be something like "KEYCODE_A" - extract the "A"

			        // use pattern to convert int keycode to some character
			        Matcher matcher = KEYCODE_PATTERN.matcher(key);
			        
			        if (matcher.matches()) {
			            // append character to textview
			        	 Scanning=Scanning+matcher.group(1);
			        //	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
			          //
			        }
			        // 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.getCountItemBarcode(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();  
		}
  }

				
			});

		}
	 
	 
	    

}
