package com.example.waoperations;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.text.Normalizer;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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



import com.bimsdk.usb.UsbConnect;
import com.bimsdk.usb.io.OnDataReceive;
import com.example.waoperations.adapter.NavDrawerListAdapter;
import com.example.waoperations.model.NavDrawerItem;
import com.example.waoperations.Inventory.InventoryAdapter;
import com.example.waoperations.Inventory.InventoryAddBarcode;
import com.example.waoperations.Inventory.InventoryDatabaseHelper;
import com.example.waoperations.Inventory.InventoryPositionChange;
import com.example.waoperations.Inventory.InventorySummary;

import com.example.waoperations.Aduanas.AduanasSummary;
import com.example.waoperations.CycleCount.CycleCountDatabaseHelper;
import com.example.waoperations.CycleCount.CycleCountSummary;
import com.example.waoperations.CycleCount.CycleCountSummaryProgrammed;
import com.example.waoperations.Picking.PickingSummary;
import com.example.waoperations.PutAway.PutAwaySummary;
import com.example.waoperations.Receiving.ReceivingSummary;
import com.example.waoperations.Shipping.ShippingSummary;

import com.example.waoperations.Stats.StatsSummary;
import com.example.waoperations.Replenishment.ReplenishmentSummary;
import com.example.waoperations.R;


import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Color;
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.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
/*import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;*/
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.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class OrderLoad extends Activity {
	
	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
	private static final int REQUEST_CODE = 1234;
	public int COUNTER =0;
	public int GLOBALCOUNTER =0;
	public String Type,USER,OPERATION,USERCODE,LASTPO,COUNTID;
	public String Scanning="";
	public int execute=0;
	public int timerstarted=0;
	public Boolean timercompleted=false;
	final Context context = this;
	final String PREFS_NAME = "MyPrefsFile";
    private UserPermissionsDatabaseHelper databaseHelper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
	setContentView(R.layout.poenter);
	ActionBar actionBar = getActionBar();
	actionBar.hide();
	
	// more stuff here...
	Intent intent = getIntent();
	Type=intent.getStringExtra("tipo");
    TextView PO = (TextView)findViewById(R.id.po);
    PO.setVisibility(View.GONE);
    TextView emptitel = (TextView)findViewById(R.id.comtitel);
    emptitel.setVisibility(View.GONE);
    TextView bodtitel = (TextView)findViewById(R.id.wartitel);
    bodtitel.setVisibility(View.GONE);
    TextView intro = (TextView)findViewById(R.id.introtext);
    intro.setVisibility(View.GONE);
    TextView eqptitel = (TextView)findViewById(R.id.equipmenttitel);
    eqptitel.setVisibility(View.GONE);
    TextView query = (TextView)findViewById(R.id.queryoperationtitel);
    query.setVisibility(View.GONE);
    Spinner empresa = (Spinner) findViewById(R.id.empresa);
    empresa.setVisibility(View.GONE);
    Spinner bodega = (Spinner) findViewById(R.id.bodega);
    bodega.setVisibility(View.GONE);
    Spinner equipment = (Spinner)findViewById(R.id.equipment);
    equipment.setVisibility(View.GONE);
    Spinner operation = (Spinner)findViewById(R.id.operation);
    operation.setVisibility(View.GONE);
	
	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	
	    String subtitle ="Picking";
	    OPERATION="Picking";
	    LASTPO=settings.getString("PickingLast", "");
        if(Type.equals("1")){
        subtitle ="Receiving";   
        OPERATION="Receiving";
        LASTPO=settings.getString("ReceivingLast", "");
        }
        if(Type.equals("2")){
        subtitle ="Putaway";  
        OPERATION="Putaway";
        LASTPO=settings.getString("PutAwayLast", "");
        }    
        if(Type.equals("3")){
        subtitle ="Shipping";
       	OPERATION="Shipping";
        LASTPO=settings.getString("ShippingLast", "");
        }  
        if(Type.equals("4")){
       	 subtitle ="Inventory"; 
         OPERATION="Inventory";
         LASTPO=settings.getString("InventoryLast", "");
       } 
        if(Type.equals("5")){
        subtitle ="Cycle count posición";
        OPERATION="CycleCount";
        intro.setText("Escanee o digite posición a inventariar:");
        LASTPO=settings.getString("CycleCountLast", "");
        }
        if(Type.equals("6")){
        subtitle ="Replenishment";
        OPERATION="Replenishment";
        intro.setText("Seleccione la empresa asociada al reabastecimiento");
        //LASTPO=settings.getString("Replenishment", "");
         }
        if(Type.equals("7")){
            subtitle ="Stats";
            OPERATION="Stats";
            intro.setText("Seleccione la categoría a analizar:");
            //LASTPO=settings.getString("Replenishment", "");
        }
        if(Type.equals("8")){
            subtitle ="Aduanas";
            OPERATION="Aduanas";
            intro.setText("Escanee o digite posición a consultar:");
            LASTPO=settings.getString("Aduanas", "");
        }
        if(Type.equals("9")){
            subtitle ="Cíclico Programado";
            OPERATION="CycleCount";
            intro.setText("Escanee o digite posición a consultar:");
            //LASTPO=settings.getString("Replenishment", "");
        }
       
        
	    actionBar.setSubtitle(subtitle);
	    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(); 
	    
		final TextView view = (TextView) findViewById(R.id.po);
		
		view.setOnClickListener(new View.OnClickListener() {
        //When you click the button, Alert dialog will be showed
        public void onClick(View v) {
       /* Alert Dialog Code Start*/ 	
        	AlertDialog.Builder alert = new AlertDialog.Builder(context);
        	alert.setTitle("Selección de orden"); //Set Alert dialog title here
        	alert.setMessage("Digite número de orden"); //Message here
 
            // Set an EditText view to get user input 
            final EditText input = new EditText(context);
        
            input.setText(LASTPO);
  
            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();
        		TextView PO = (TextView)findViewById(R.id.po);
        		PO.setText(srt);
        	} // 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();
       /* Alert Dialog Code End*/        
     }// End of onClick(View v)
  });
		
		GetData();
		if (!UsbConnect.isConnect(this)) {
			UsbConnect.Connect(this);
		}

		}
	

	  @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
	        
	    	new CountDownTimer(1000, 1000) {       
				   public void onTick(long millisUntilFinished) {          
				}       

				public void onFinish() {   
					if(execute==1){
					execute=0;
					
				     if(COUNTER==0){
		                	TextView user = (TextView)findViewById(R.id.user);
		                	databaseHelper = new UserPermissionsDatabaseHelper(context.getApplicationContext()); 
		                    StrictMode.setThreadPolicy(policy); 
		                		try{
		                			
		                			String result = null;
		                	    	InputStream is = null;
		                	  
		                	    	String v1 = "'"+Scanning+"'";
		                			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
		                			String v2 = ""+OPERATION+"";

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

		                	//apartir de aqui carga ruta
		                		try
		                		{
		                	    	        HttpClient httpclient = new DefaultHttpClient();
		                	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/checkUser.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 usuario=no.getString("Nombre");
		                	    		    USER=usuario;
		                	    		    user.setText(usuario);
		                	    		    String war=no.getString("Warehouse");
		                	    		    String com=no.getString("Company");
		                	    		    String equ=no.getString("Equipment");
		                	    		   
		                		            NumberFormat nf = NumberFormat.getInstance();
		                		            nf.setMaximumFractionDigits(0);// set as you need
		                	                //databaseHelper.savePickLine(po,loc,sku,"-",qty,type,"0","0",barcode,country);
		                	            	databaseHelper.savePermissions(Scanning, war, com,equ);

		                		            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.");
		                		}
		                		Cursor x =databaseHelper.getAllUserPermissionLines(Scanning);
		                		if(x.getCount()==0){
		                			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                          	// Vibrate for 400 milliseconds
	                          	v.vibrate(400);
	                          	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
		                	    Toast.makeText(getBaseContext(), "Usuario no existente o no tiene permisos para accesar esta operación.", Toast.LENGTH_LONG).show();
		                		}else{
		                	    	Spinner empresa = (Spinner) findViewById(R.id.empresa);
		                	    	empresa.setVisibility(View.VISIBLE);
		                	    	Spinner bodega = (Spinner) findViewById(R.id.bodega);
		                	    	bodega.setVisibility(View.VISIBLE);
		                	     	TextView emptitel = (TextView)findViewById(R.id.comtitel);
		                	      	emptitel.setVisibility(View.VISIBLE);
		                	      	TextView bodtitel = (TextView)findViewById(R.id.wartitel);
		                	      	bodtitel.setVisibility(View.VISIBLE);
		                 			x.moveToFirst();
		                	        if(Type.equals("4")){
		                	        	Spinner equipment = (Spinner) findViewById(R.id.operation);
		                	        	equipment.setVisibility(View.VISIBLE);
			                	     	TextView eqptitel = (TextView)findViewById(R.id.queryoperationtitel);
			                	     	eqptitel.setVisibility(View.VISIBLE);
			                    		
			                    		// Create an ArrayAdapter using the string array and a default spinner layout
			                    		ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(context,
			                    		        R.array.operations_array, android.R.layout.simple_spinner_item);
			                    		// 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
			                    		equipment.setAdapter(adapter3);
	
		                	          }
		                	        
		                	        else if(Type.equals("0")){
		                	        	Spinner equipment = (Spinner) findViewById(R.id.equipment);
		                	        	equipment.setVisibility(View.VISIBLE);
			                	     	TextView eqptitel = (TextView)findViewById(R.id.equipmenttitel);
			                	     	eqptitel.setVisibility(View.VISIBLE);
			                	     	String[] equipos =  x.getString(4).split(";");
			                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, equipos);
			                    		// 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);
			                    		TextView intro = (TextView)findViewById(R.id.introtext);
			                	      	intro.setVisibility(View.VISIBLE);
	                	        		TextView PO = (TextView)findViewById(R.id.po);
			                	      	PO.setVisibility(View.VISIBLE);  
			                	      	
			                	    	Spinner OPERACION = (Spinner) findViewById(R.id.operation);
			                	    	OPERACION.setVisibility(View.VISIBLE);
			                	     	TextView operacion = (TextView)findViewById(R.id.queryoperationtitel);
			                	     	operacion.setVisibility(View.VISIBLE);
			                    		
			                    		// Create an ArrayAdapter using the string array and a default spinner layout
			                    		ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(context,
			                    		        R.array.sort_array, android.R.layout.simple_spinner_item);
			                    		// 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
			                    		OPERACION.setAdapter(adapter3);
		                	          }
		                	        else if(Type.equals("6")){
		                	        	
			                    		TextView intro = (TextView)findViewById(R.id.introtext);
			                	      	intro.setVisibility(View.VISIBLE);
	                	     
		                	          } 
		                	        else if(Type.equals("7")){
		                	        	empresa.setVisibility(View.INVISIBLE);
			                	    
			                	    	bodega.setVisibility(View.INVISIBLE);
			                	    	
			                	      	emptitel.setVisibility(View.INVISIBLE);
			                	      	bodtitel.setVisibility(View.INVISIBLE);
			                	  
				                	     
			                    		TextView intro = (TextView)findViewById(R.id.introtext);
			                	      	intro.setVisibility(View.INVISIBLE);
	                	         
		                	          } 
		                	        else if(Type.equals("9")){
		                	        	empresa.setVisibility(View.INVISIBLE);
			                	    
			                	    	bodega.setVisibility(View.INVISIBLE);
			                	    	
			                	      	emptitel.setVisibility(View.INVISIBLE);
			                	      	bodtitel.setVisibility(View.INVISIBLE);
			                	  
				                	     
			                    		TextView intro = (TextView)findViewById(R.id.introtext);
			                	      	intro.setVisibility(View.INVISIBLE);
	                	         
		                	          } 
		                	        else{
		                	     	     	TextView intro = (TextView)findViewById(R.id.introtext);
				                	      	intro.setVisibility(View.VISIBLE);
		                	        		TextView PO = (TextView)findViewById(R.id.po);
				                	      	PO.setVisibility(View.VISIBLE);    
		                	          }
		               
		                           	String[] bodegas = x.getString(2).split(";");
		                           	String[] empresas =  x.getString(3).split(";");

		                    		// Create an ArrayAdapter using the string array and a default spinner layout
		                    		ArrayAdapter adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, empresas);
		                    		// Specify the layout to use when the list of choices appears
		                    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		                    		// Apply the adapter to the spinner
		                    		empresa.setAdapter(adapter);

		                    		// Create an ArrayAdapter using the string array and a default spinner layout
		                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bodegas);
		                    		// 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
		                    		bodega.setAdapter(adapter2);
		                    		
		                	    	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));		
		                	    	   COUNTER++;
		                		}


		               }
		               else if(COUNTER==1){
		            	TextView PO = (TextView)findViewById(R.id.po);
			            PO.setText(Scanning);

		               }
		      	      Scanning="";
					}
				
				}
				   
				}.start();  
	        
	        return super.onKeyDown(keyCode, event);
	    }
		
	 public void onStart(View view) {  
		 	TextView PO = (TextView)findViewById(R.id.po);
       	    String po=PO.getText().toString();
	      if(COUNTER==0){
		       	Toast.makeText(getApplicationContext(), "Verifique su código para avanzar.", Toast.LENGTH_SHORT).show();
				   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
   			   intentemoslo.putExtra("voz","Verifique su código para avanzar");
   				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
              	// Vibrate for 400 milliseconds
              	v.vibrate(400);
   			   startService(intentemoslo);	
		         
	      }
	      
	    
	      else{
		        Spinner empresa = (Spinner)findViewById(R.id.empresa);
		        String Emp = empresa.getSelectedItem().toString();
  
		        Spinner bodega = (Spinner)findViewById(R.id.bodega);
		        String Bod = bodega.getSelectedItem().toString();

		       	po=PO.getText().toString();
		       	
		        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  	 
			    Intent intento = new Intent(getApplicationContext(), PickingSummary.class);
			    if(Type.equals("0")){
		        settings.edit().putString("PickingLast", po).commit();
		        }
                if(Type.equals("1")){
                intento = new Intent(getApplicationContext(), ReceivingSummary.class);  
                settings.edit().putString("ReceivingLast", po).commit();
                }
                if(Type.equals("2")){
                intento = new Intent(getApplicationContext(), PutAwaySummary.class);
                settings.edit().putString("PutAwayLast", po).commit();
                }    
                if(Type.equals("3")){
                intento = new Intent(getApplicationContext(), ShippingSummary.class); 
                settings.edit().putString("ShippingLast", po).commit();
                }  
                if(Type.equals("5")){
                intento = new Intent(getApplicationContext(), CycleCountSummary.class);  
                //Mientras tanto para conteo cíclico programado
                settings.edit().putString("CycleCountLast", po).commit();
                }
                if(Type.equals("6")){
                intento = new Intent(getApplicationContext(), ReplenishmentSummary.class);  
                settings.edit().putString("Replenishment", po).commit();
                }
                if(Type.equals("7")){
                    intento = new Intent(getApplicationContext(), StatsSummary.class);  
                 }
                if(Type.equals("8")){
                    intento = new Intent(getApplicationContext(), AduanasSummary.class);  
                    settings.edit().putString("Aduanas", po).commit();
                 }
                if(Type.equals("9")){
                    
                  	 StrictMode.setThreadPolicy(policy); 
             	    
             		try{
             			
             			String result = null;
             	    	InputStream is = null;

             			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");

             			String v3 = "'"+USER+"'"; 

             	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
             	     	nameValuePairs.add(new BasicNameValuePair("user",v3));

             	//apartir de aqui carga ruta
             		try
             		{
             	    	        HttpClient httpclient = new DefaultHttpClient();
             	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Cyclecount/getItemCycleCount.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{
                         

             	    	 	JSONArray jArray = new JSONArray(result);
             	    		for(int i=0;i<jArray.length();i++)  
             	            {
             	    			try{
             	    		   	JSONObject no = jArray.getJSONObject(i);
             	    		    String SKU=no.getString("ITEMID");
             	    		   String WAREHOUSE=no.getString("WAREHOUSE");
             	    		    po=SKU;
             	    	       Bod=WAREHOUSE;
             	    		    String DATAAREAID=no.getString("DATAAREAID");
             	    		    Emp=DATAAREAID;
             	    		    COUNTID=no.getString("COUNTID");
             	    		
             	    			}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.");
             		}
                       
             			intento = new Intent(getApplicationContext(), CycleCountSummaryProgrammed.class);  	
                
             			intento.putExtra("COUNTID",COUNTID);

                       }
              
                if(Type.equals("4")){
                Spinner op = (Spinner)findViewById(R.id.operation);
                settings.edit().putString("InventoryLast", po).commit();
                if(op.getSelectedItemPosition()==1){
                intento = new Intent(getApplicationContext(), InventoryPositionChange.class);  	
            	
            }else if(op.getSelectedItemPosition()==0){
            
            intento = new Intent(getApplicationContext(), InventorySummary.class);  	
            }else{
            intento = new Intent(getApplicationContext(), InventoryAddBarcode.class);  	
            }
            }
            if(Type.equals("0")){
            Spinner equipment = (Spinner)findViewById(R.id.equipment);
            String equip = equipment.getSelectedItem().toString();
            intento.putExtra("EQUIPO",equip);
            intento.putExtra("PO",po);
            Spinner op = (Spinner)findViewById(R.id.operation);
            intento.putExtra("REVERSE","0");
            if(op.getSelectedItemPosition()==1){
            intento.putExtra("REVERSE","1");
             }
            }
     
            else{
		    intento.putExtra("PO",po);}
		    intento.putExtra("EMP",Emp);
		    intento.putExtra("BOD",Bod);
		    intento.putExtra("USER",USER);
		    intento.putExtra("USERCODE",USERCODE);
		    startActivity(intento);	  
			}
	 }
	  
	  @Override
	 public boolean onCreateOptionsMenu(Menu menu) {
	        // Inflate the menu items for use in the action bar
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.addcontact
	        ,menu);
	        return super.onCreateOptionsMenu(menu);
	    }
	   
	  @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 user = (TextView)findViewById(R.id.user);
			                	databaseHelper = new UserPermissionsDatabaseHelper(this.getApplicationContext()); 
			                    StrictMode.setThreadPolicy(policy); 
			                		try{
			                			String result = null;
			                	    	InputStream is = null;
			                	    	String v1 = "'"+contents+"'";
			                	    	String v2 = ""+OPERATION+"";
			                			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
			                	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			                	     	nameValuePairs.add(new BasicNameValuePair("codigo",v1));
			                	     	nameValuePairs.add(new BasicNameValuePair("operacion",v2));
			                	//apartir de aqui carga ruta
			                		try
			                		{
			                	    	        HttpClient httpclient = new DefaultHttpClient();
			                	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/checkUser.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;
			                	    	try{
			                	            databaseHelper.deleteAllData();
			                	    	 	JSONArray jArray = new JSONArray(result);
			                	    		for(int i=0;i<jArray.length();i++)  
			                	            {
			                	    			try{
			                	    		   	JSONObject no = jArray.getJSONObject(i);
			                	    		    String usuario=no.getString("Nombre");
			                	    		    USER=usuario;
			                	    		    user.setText(usuario);
			                	    		    String war=no.getString("Warehouse");
			                	    		    String com=no.getString("Company");
			                	    		    String equ=no.getString("Equipment");
			                	    		    
			                		            NumberFormat nf = NumberFormat.getInstance();
			                		            nf.setMaximumFractionDigits(0);// set as you need
			                	                //databaseHelper.savePickLine(po,loc,sku,"-",qty,type,"0","0",barcode,country);
			                	            	databaseHelper.savePermissions(contents, war, com,equ);
			                		            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.");
			                		}
			                		Cursor x =databaseHelper.getAllUserPermissionLines(contents);
			                		if(x.getCount()==0){
			                			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                            	// Vibrate for 400 milliseconds
		                            	v.vibrate(400);
		                            	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
			                	    Toast.makeText(getBaseContext(), "Usuario no existente.", Toast.LENGTH_LONG).show();	
			                		}else{

			                	    	Spinner empresa = (Spinner) findViewById(R.id.empresa);
			                	    	empresa.setVisibility(View.VISIBLE);
			                	    	Spinner bodega = (Spinner) findViewById(R.id.bodega);
			                	    	bodega.setVisibility(View.VISIBLE);
			                	     	TextView emptitel = (TextView)findViewById(R.id.comtitel);
			                	      	emptitel.setVisibility(View.VISIBLE);
			                	      	TextView bodtitel = (TextView)findViewById(R.id.wartitel);
			                	      	bodtitel.setVisibility(View.VISIBLE);
			                	      	x.moveToFirst();
			                	        if(Type.equals("4")){
			                	          	
			                	          }
			                	        
			                	        if(Type.equals("0")){
			                	        	Spinner equipment = (Spinner) findViewById(R.id.equipment);
			                	        	equipment.setVisibility(View.VISIBLE);
				                	     	TextView eqptitel = (TextView)findViewById(R.id.equipmenttitel);
				                	     	eqptitel.setVisibility(View.VISIBLE);
				                	     	String[] equipos =  x.getString(4).split(";");
				                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, equipos);
				                    		// 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);
				                    		TextView intro = (TextView)findViewById(R.id.introtext);
				                	      	intro.setVisibility(View.VISIBLE);
		                	        		TextView PO = (TextView)findViewById(R.id.po);
				                	      	PO.setVisibility(View.VISIBLE);  
			                	          }
			                	        else{
			                	     	     	TextView intro = (TextView)findViewById(R.id.introtext);
					                	      	intro.setVisibility(View.VISIBLE);
			                	        		TextView PO = (TextView)findViewById(R.id.po);
					                	      	PO.setVisibility(View.VISIBLE);    
			                	          }
			                           	String[] bodegas = x.getString(2).split(";");
			                           	String[] empresas =  x.getString(3).split(";");
			                           	
			                    		
			                    		// Create an ArrayAdapter using the string array and a default spinner layout
			                    		ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, empresas);
			                    		// Specify the layout to use when the list of choices appears
			                    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			                    		// Apply the adapter to the spinner
			                    		empresa.setAdapter(adapter);

			                    		// Create an ArrayAdapter using the string array and a default spinner layout
			                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, bodegas);
			                    		// 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
			                    		bodega.setAdapter(adapter2);

			                	    	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));		
			                	    	   COUNTER++;
			                		}


			               }
			               else if(COUNTER==1){
			            	TextView PO = (TextView)findViewById(R.id.po);
				            PO.setText(contents);

			               }

					    }}

			  
			 }
    
	 @Override
  	 public boolean onOptionsItemSelected(MenuItem item) {
	        // Handle presses on the action bar items

	        switch (item.getItemId()) {
	            case R.id.add:
	       		 if(execute==0){
	       			
	            		try{
		                Intent intent = new Intent(
		      	        "com.google.zxing.client.android.SCAN");
		      	        //intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
		      	        startActivityForResult(intent, 0);
	            		 }catch(Exception e){ 
	     	       		Toast.makeText(getApplicationContext(), "Debe instalar ZXING para utilizar esta opción.", Toast.LENGTH_SHORT).show();
	     	       		}
		                return true;

	       		 }else{ 
	       		 // Toast.makeText(getApplicationContext(), Scanning, Toast.LENGTH_SHORT).show();
	        }
	            default:
	            return super.onOptionsItemSelected(item);
	        }
	    }
	 
	 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 user = (TextView)findViewById(R.id.user);
					                	databaseHelper = new UserPermissionsDatabaseHelper(context.getApplicationContext()); 
					                    StrictMode.setThreadPolicy(policy); 
					                		try{
					                			String result = null;
					                	    	InputStream is = null;
					                	    	String v1 = "'"+Scanning+"'";
					                			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
					                			String v2 = ""+OPERATION+"";
					                	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					                	     	nameValuePairs.add(new BasicNameValuePair("codigo",v1));
					                	       	nameValuePairs.add(new BasicNameValuePair("operacion",v2));
					                		    try
					                		    {
					                	    	        HttpClient httpclient = new DefaultHttpClient();
					                	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/checkUser.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 usuario=no.getString("Nombre");
					                	    		    USER=usuario;
					                	    		    user.setText(usuario);
					                	    		    String war=no.getString("Warehouse");
					                	    		    String com=no.getString("Company");
					                	    		    String equ=no.getString("Equipment");
					                		            NumberFormat nf = NumberFormat.getInstance();
					                		            nf.setMaximumFractionDigits(0);// set as you need
					                	                //databaseHelper.savePickLine(po,loc,sku,"-",qty,type,"0","0",barcode,country);
					                	            	databaseHelper.savePermissions(Scanning, war, com,equ);
					                		            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.");
					                		}
					                		Cursor x =databaseHelper.getAllUserPermissionLines(Scanning);
					                		if(x.getCount()==0){
					                			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				                          	// Vibrate for 400 milliseconds
				                          	v.vibrate(400);
				                          	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
					                	    Toast.makeText(getBaseContext(), "Usuario no existente o no tiene permisos para accesar esta operación.", Toast.LENGTH_LONG).show();
					                		}else{
					                			
					                	    	Spinner empresa = (Spinner) findViewById(R.id.empresa);
					                	    	empresa.setVisibility(View.VISIBLE);
					                	    	Spinner bodega = (Spinner) findViewById(R.id.bodega);
					                	    	bodega.setVisibility(View.VISIBLE);
					                	     	TextView emptitel = (TextView)findViewById(R.id.comtitel);
					                	      	emptitel.setVisibility(View.VISIBLE);
					                	      	TextView bodtitel = (TextView)findViewById(R.id.wartitel);
					                	      	bodtitel.setVisibility(View.VISIBLE);
					                	      	x.moveToFirst();
					                	      	
					                	        if(Type.equals("4")){
					                	          	
					                	          }
					                	        
					                	        else if(Type.equals("0")){
					                	        	Spinner equipment = (Spinner) findViewById(R.id.equipment);
					                	        	equipment.setVisibility(View.VISIBLE);
						                	     	TextView eqptitel = (TextView)findViewById(R.id.equipmenttitel);
						                	     	eqptitel.setVisibility(View.VISIBLE);
						                	     	String[] equipos =  x.getString(4).split(";");
						                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, equipos);
						                    		// 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);
						                    		TextView intro = (TextView)findViewById(R.id.introtext);
						                	      	intro.setVisibility(View.VISIBLE);
				                	        		TextView PO = (TextView)findViewById(R.id.po);
						                	      	PO.setVisibility(View.VISIBLE);  
					                	          }
					                	        else{
					                	     	     	TextView intro = (TextView)findViewById(R.id.introtext);
							                	      	intro.setVisibility(View.VISIBLE);
					                	        		TextView PO = (TextView)findViewById(R.id.po);
							                	      	PO.setVisibility(View.VISIBLE);    
					                	          }
					                           	String[] bodegas = x.getString(2).split(";");
					                           	String[] empresas =  x.getString(3).split(";");
					                           	
					                    		
					                    		// Create an ArrayAdapter using the string array and a default spinner layout
					                    		ArrayAdapter adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, empresas);
					                    		// Specify the layout to use when the list of choices appears
					                    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					                    		// Apply the adapter to the spinner
					                    		empresa.setAdapter(adapter);
					                    	
					                    		// Create an ArrayAdapter using the string array and a default spinner layout
					                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bodegas);
					                    		// 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
					                    		bodega.setAdapter(adapter2);
					                           	
					                	    	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));		
					                	    	   COUNTER++;
					                		}


					               }
					               else if(COUNTER==1){
					            	TextView PO = (TextView)findViewById(R.id.po);
						            PO.setText(Scanning);

					               }
			                      timerstarted=0;
					      	      Scanning="";
					      	      timercompleted=false;
							  }
							}
						
						
						
						}}.start();  
						}
				  }
				
			});

		}

	 
}	
	 