/*
 * Copyright 2012 Indigo Rose Software Design Corporation
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.example.waoperations.Inventory;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.Normalizer;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import com.bimsdk.usb.UsbConnect;
import com.bimsdk.usb.io.OnDataReceive;
import com.example.waoperations.R;
import com.example.waoperations.UserPermissionsDatabaseHelper;
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.animation.ObjectAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
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.Handler;
import android.os.StrictMode;
import android.os.SystemClock;
import android.os.Vibrator;


import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TypefaceSpan;
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.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Main UI for the demo app.
 */
public class InventorySummary extends Activity {
    public String client;
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    TextView mDisplay;
    private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
    InventoryAdapter newInventoryAdapter;
    public String LOCATION,EMP,BOD,CONT;
    public View header;
    public int tipo;
	public String Scanning="";
    public int timerstarted=0;
	public Boolean timercompleted=false;
	public int execute=0;
    final Context context = this;

    private static final String tag = "Main";


    private InventoryDatabaseHelper databaseHelper;
    //private static final String TAG = "DemoActivity";
    
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inventorylist);
        
        header = getLayoutInflater().inflate(R.layout.header_inventory, null);
        TextView HeaderName = (TextView) header.findViewById(R.id.tableroheader);
    	Intent intent = getIntent();
    	HeaderName.setFocusable(true);
    	//HeaderName.setIconified(false);
    	HeaderName.requestFocusFromTouch();
		EMP=intent.getStringExtra("EMP");
		BOD=intent.getStringExtra("BOD");
		
        HeaderName.setText("INVENTARIO:POSICIÓN");
        
        tipo=0;
	    ListView listView = (ListView)findViewById(R.id.inventorylistview);


	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    
	actionBar.setSubtitle("Inventory");
	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(true);
	actionBar.show(); 

    Typeface fontbold = Typeface.createFromAsset(this.getApplicationContext().getAssets(), "fonts/opensans-extrabold.ttf"); 
	HeaderName.setTypeface(fontbold);
	listView.addHeaderView(header);
	listView.setAdapter(newInventoryAdapter);
	listView.setCacheColorHint(Color.TRANSPARENT);
	databaseHelper = new InventoryDatabaseHelper(this.getApplicationContext()); 
	databaseHelper.deleteAllData();

	
	final TextView view =(TextView) header.findViewById(R.id.position);
	
	
	
	
	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 ítem/posición"); //Set Alert dialog title here
    	alert.setMessage("Digite ítem/posición"); //Message here

        // Set an EditText view to get user input 
        final EditText input = new EditText(context);
        alert.setView(input);

    	alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    	public void onClick(DialogInterface dialog, int whichButton) {
    	 //You will get as string input data in this variable.
    	 // here we convert the input to a string and show in a toast.
    	 String srt = input.getEditableText().toString().toUpperCase();
    		//TextView PO = (TextView) header.findViewById(R.id.position);
    		//PO.setText(srt);
    		
    	 databaseHelper = new InventoryDatabaseHelper(context); 
    	 	ListView listView = (ListView)findViewById(R.id.inventorylistview);
		 	listView.setAdapter(null);
         
    	    TextView location = (TextView) header.findViewById(R.id.position);
    	
    	    
    	    databaseHelper.deleteAllData();
    	    StrictMode.setThreadPolicy(policy); 
            if(tipo==0){  LOCATION=srt;   }
    		try{
				
				String result = null;
	        	InputStream is = null;
	      
	        	String v1 = "'"+EMP+"'";
	    		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");

			String v2 = "'"+BOD+"'"; 
			String v3 = "'"+srt+"'"; 

	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
	        nameValuePairs.add(new BasicNameValuePair("UID",v3));
	        
	//apartir de aqui carga ruta
	 	
	  	try
	   	{
	        	        HttpClient httpclient = new DefaultHttpClient();
	        	        HttpPost httppost = new HttpPost("http://10.10.100.13/getInventoryPerLocation.php");
	        	        if(tipo==1){
	        	        	httppost = new HttpPost("http://10.10.100.13/getInventoryPerItemID.php");   }
	        	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	        	        HttpResponse response = httpclient.execute(httppost); 
	        	        HttpEntity entity = response.getEntity();
	        	        is = entity.getContent();

	        	        Log.e("log_tag", "connection success ");
	        	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
	   	}
	   catch(Exception e)
	   	{
	        	        Log.e("log_tag", "Error in http connection "+e.toString());
	        	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
	        	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
	   	}
	        	//convert response to string
	   	try{
	   		
	        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
	        	        StringBuilder sb = new StringBuilder();
	        	        String line = null;
	        	        while ((line = reader.readLine()) != null) 
	        	        {
	        	                sb.append(line + "\n");
	        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
	        	        }
	        	        is.close();
	        	        result=sb.toString();
	   	}
	   	catch(Exception e)
	   	{
	        	       Log.e("log_tag", "Error converting result "+e.toString());
	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
	   	}
	int counter=0;
	        	//parse json data
	        	try{

	        	 	JSONArray jArray = new JSONArray(result);
	        		for(int i=0;i<jArray.length();i++)  
		        {
	        			try{
	        		   	JSONObject no = jArray.getJSONObject(i);    
	        		    String loc=no.getString("Location");
	        		    String sku=no.getString("itemID");
	        			//String descripcion=   Normalizer.normalize(no.getString("Description"), Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
	        		    String qty=no.getString("qty");
	        		    try{
	        		    Double Qt = Double.parseDouble(qty);
	        		    NumberFormat nf = NumberFormat.getInstance();
		 	            nf.setMaximumFractionDigits(0);// set as you need
	        		    qty=nf.format(Qt).replace(",", "");
	        		    }catch(Exception e){}
	        		    String type=no.getString("dim");
	          		    String country=no.getString("country");
	             		  String weight=no.getString("weight");
		        		    try{
			        		    Double Qt = Double.parseDouble(weight);
			        		    NumberFormat nf = NumberFormat.getInstance();
				 	            nf.setMaximumFractionDigits(8);// set as you need
				 	           weight=nf.format(Qt).replace(",", "");
			        		    }catch(Exception e){}
		 	                String volume=no.getString("vol");
		        		    try{
			        		    Double Qt = Double.parseDouble(volume);
			        		    NumberFormat nf = NumberFormat.getInstance();
				 	            nf.setMaximumFractionDigits(8);// set as you need
				 	           volume=nf.format(Qt).replace(",", "");
			        		    }catch(Exception e){}
		 	         
	 	         
		        		    databaseHelper.saveInventoryLine(loc, sku, "", qty, type, country,weight, volume);
	 	                LOCATION=sku;    
	 	                if(tipo==0){  LOCATION=loc;   }
	 	                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.");
        	}
    	    
    	    location.setText(LOCATION);
        	Cursor x =databaseHelper.getInventoryLines(LOCATION);
     	    if(tipo==1){x=databaseHelper.getInventoryItemLines(LOCATION);}
        	if(x.getCount()<=0){
        	if(tipo==0){
            Toast.makeText(getBaseContext(), "Ubicación no existente.", Toast.LENGTH_LONG).show();}
        	else{
        	Toast.makeText(getBaseContext(), "Artículo no existente.", Toast.LENGTH_LONG).show();	
        	}
            TextView Weight = (TextView) header.findViewById(R.id.weight);
            Weight.setText("Peso: 0");
            Typeface fontbold2 = Typeface.createFromAsset(context.getAssets(), "fonts/opensans-semibold.ttf"); 
            Weight.setTypeface(fontbold2);
            TextView Volume = (TextView) header.findViewById(R.id.volume);
            Volume.setText("Volumen: 0");
            Volume.setTypeface(fontbold2);
            location.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
        	}
        	else{
        	
                double totalweight=0;double totalvolume=0;double locweight=0;double locvolume=0;
        		while (x.moveToNext()) {
        		double indqty=Double.parseDouble(x.getString(4));
        		totalweight=totalweight+indqty*Double.parseDouble(x.getString(7));
        		totalvolume=totalvolume+indqty*Double.parseDouble(x.getString(8));
        		}
        		NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(3);// set as you need
                TextView Weight = (TextView) header.findViewById(R.id.weight);
                Weight.setText("Peso: "+nf.format(totalweight));
                Typeface fontbold2 = Typeface.createFromAsset(context.getAssets(), "fonts/opensans-semibold.ttf"); 
                Weight.setTypeface(fontbold2);
                TextView Volume = (TextView) header.findViewById(R.id.volume);
                Volume.setText("Volumen: "+nf.format(totalvolume));
                Volume.setTypeface(fontbold2);
                location.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
        	}
        	
		 	if(tipo==0){
			 	newInventoryAdapter = new InventoryAdapter(context,databaseHelper.getInventoryLines(LOCATION));
			 	}else if(tipo==1){
			    newInventoryAdapter = new InventoryAdapter(context,databaseHelper.getInventoryItemLines(LOCATION)); 		
			 	}
        	listView.setAdapter(newInventoryAdapter);
	
    	} // 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.scanandswap
        		, 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");
		            	databaseHelper = new InventoryDatabaseHelper(this.getApplicationContext()); 
		        	 	ListView listView = (ListView)findViewById(R.id.inventorylistview);
		    		 	listView.setAdapter(null);
		             
		        	    TextView location = (TextView) header.findViewById(R.id.position);
		        	
		        	    
		        	    databaseHelper.deleteAllData();
		        	    StrictMode.setThreadPolicy(policy); 
		                if(tipo==0){  LOCATION=contents;   }
		        		try{
		    				
							String result = null;
				        	InputStream is = null;
				      
				        	String v1 = "'"+EMP+"'";
				    		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");

						String v2 = "'"+BOD+"'"; 
						String v3 = "'"+contents+"'"; 

				        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/getInventoryPerLocation.php");
				        	        if(tipo==1){ httppost = new HttpPost("http://10.10.100.13/getInventoryPerItem.php");   }
				        	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				        	        HttpResponse response = httpclient.execute(httppost); 
				        	        HttpEntity entity = response.getEntity();
				        	        is = entity.getContent();

				        	        Log.e("log_tag", "connection success ");
				        	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
				   	}
				   catch(Exception e)
				   	{
				        	        Log.e("log_tag", "Error in http connection "+e.toString());
				        	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
				        	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
				   	}
				        	//convert response to string
				   	try{
				   		
				        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
				        	        StringBuilder sb = new StringBuilder();
				        	        String line = null;
				        	        while ((line = reader.readLine()) != null) 
				        	        {
				        	                sb.append(line + "\n");
				        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
				        	        }
				        	        is.close();
				        	        result=sb.toString();
				   	}
				   	catch(Exception e)
				   	{
				        	       Log.e("log_tag", "Error converting result "+e.toString());
				       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
				   	}
				int counter=0;
				        	//parse json data
				        	try{

				        	 	JSONArray jArray = new JSONArray(result);
				        		for(int i=0;i<jArray.length();i++)  
					        {
				        			try{
				        		   	JSONObject no = jArray.getJSONObject(i);    
				        		    String loc=no.getString("Location");
				        		    String sku=no.getString("itemID");
				        			//String descripcion=   Normalizer.normalize(no.getString("Description"), Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
				        		    String qty=no.getString("qty");
				        		    try{
				        		    Double Qt = Double.parseDouble(qty);
				        		    NumberFormat nf = NumberFormat.getInstance();
					 	            nf.setMaximumFractionDigits(0);// set as you need
				        		    qty=nf.format(Qt).replace(",", "");
				        		    }catch(Exception e){}
				        		    String type=no.getString("dim");
				          		    String country=no.getString("country");
				          		    
				          		  String weight=no.getString("weight");
				        		    try{
					        		    Double Qt = Double.parseDouble(weight);
					        		    NumberFormat nf = NumberFormat.getInstance();
						 	            nf.setMaximumFractionDigits(8);// set as you need
						 	           weight=nf.format(Qt).replace(",", "");
					        		    }catch(Exception e){}
				 	                String volume=no.getString("vol");
				        		    try{
					        		    Double Qt = Double.parseDouble(volume);
					        		    NumberFormat nf = NumberFormat.getInstance();
						 	            nf.setMaximumFractionDigits(8);// set as you need
						 	           volume=nf.format(Qt).replace(",", "");
					        		    }catch(Exception e){}
				 	         
				 	                databaseHelper.saveInventoryLine(loc, sku, "", qty, type, country,weight,volume);
				 	                LOCATION=sku;    
				 	                if(tipo==0){  LOCATION=loc;   }
				 	                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.");
			        	}
		        	    
		        	    
		        	    location.setText(LOCATION);
		            	Cursor x =databaseHelper.getInventoryLines(LOCATION);
		         	    if(tipo==1){x=databaseHelper.getInventoryItemLines(LOCATION);}
		            	if(x.getCount()<=0){
		            	if(tipo==0){
		                Toast.makeText(getBaseContext(), "Ubicación no existente.", Toast.LENGTH_LONG).show();}
		            	else{
		            	Toast.makeText(getBaseContext(), "Artículo no existente.", Toast.LENGTH_LONG).show();	
		            	}
		                TextView Weight = (TextView) header.findViewById(R.id.weight);
		                Weight.setText("Peso(g): 0");
		                Typeface fontbold2 = Typeface.createFromAsset(this.getApplicationContext().getAssets(), "fonts/opensans-semibold.ttf"); 
		                Weight.setTypeface(fontbold2);
		                TextView Volume = (TextView) header.findViewById(R.id.volume);
		                Volume.setText("Volumen(cm3): 0");
		                Volume.setTypeface(fontbold2);
		                location.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
		            	}
		            	else{
		            	
		                    double totalweight=0;double totalvolume=0;double locweight=0;double locvolume=0;
		            		while (x.moveToNext()) {
		            		double indqty=Double.parseDouble(x.getString(4));
		            		totalweight=totalweight+indqty*Double.parseDouble(x.getString(7));
		            		totalvolume=totalvolume+indqty*Double.parseDouble(x.getString(8));
		            		}
		            		NumberFormat nf = NumberFormat.getInstance();
		                    nf.setMaximumFractionDigits(3);// set as you need
		                    TextView Weight = (TextView) header.findViewById(R.id.weight);
		                    Weight.setText("Peso(g): "+nf.format(totalweight));
		                    Typeface fontbold2 = Typeface.createFromAsset(this.getApplicationContext().getAssets(), "fonts/opensans-semibold.ttf"); 
		                    Weight.setTypeface(fontbold2);
		                    TextView Volume = (TextView) header.findViewById(R.id.volume);
		                    Volume.setText("Volumen(cm3): "+nf.format(totalvolume));
		                    Volume.setTypeface(fontbold2);
		                    location.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
		            	}
		            	
		    		 	if(tipo==0){
		    			 	newInventoryAdapter = new InventoryAdapter(this.getApplicationContext(),databaseHelper.getInventoryLines(LOCATION));
		    			 	}else if(tipo==1){
		    			    newInventoryAdapter = new InventoryAdapter(this.getApplicationContext(),databaseHelper.getInventoryItemLines(LOCATION)); 		
		    			 	}
		            	listView.setAdapter(newInventoryAdapter);
				    }
		 }}

    
    
    
    @Override
   	  public boolean onOptionsItemSelected(MenuItem item) {
	        // Handle presses on the action bar items
	        switch (item.getItemId()) {
	        
	            case R.id.add:
	
	                Intent intent = new Intent(
	      	        "com.google.zxing.client.android.SCAN");
	      	 
	      	        startActivityForResult(intent, 0);
	     
	                return true;
	            case R.id.refresh:
	       	
	            	   if(tipo==0){
	            	   TextView HeaderName = (TextView) header.findViewById(R.id.tableroheader);
	                   HeaderName.setText("INVENTARIO:íTEM");
	                   TextView subtitle = (TextView) header.findViewById(R.id.searchtitle);
	                   subtitle.setText("Escanee o digite ítem:");
	                   tipo=1;
	            	   }   else if(tipo==1){
		            	   TextView HeaderName = (TextView) header.findViewById(R.id.tableroheader);
		                   HeaderName.setText("INVENTARIO:POSICIÃ“N");
		                   TextView subtitle = (TextView) header.findViewById(R.id.searchtitle);
		                   subtitle.setText("Escanee o digite posición:");
		                   tipo=0;
		            	   }

	                return true;
	       
	            default:
	                return super.onOptionsItemSelected(item);
	        }
	    }
    @Override
  
  public void onResume() {
        super.onResume();  // Always call the superclass method first
            // Get the Camera instance as the activity achieves full user focus
		 	ListView listView = (ListView)findViewById(R.id.inventorylistview);
		 	listView.setAdapter(null);
		 	if(tipo==0){
		 	newInventoryAdapter = new InventoryAdapter(this.getApplicationContext(),databaseHelper.getInventoryLines(LOCATION));
		 	}else if(tipo==1){
		    newInventoryAdapter = new InventoryAdapter(this.getApplicationContext(),databaseHelper.getInventoryItemLines(LOCATION)); 		
		 	}
		  	listView.setAdapter(newInventoryAdapter);
			listView.setCacheColorHint(Color.TRANSPARENT);
        }
  
    @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;
				CONT=Scanning;
		    	databaseHelper = new InventoryDatabaseHelper(context); 
        	 	ListView listView = (ListView)findViewById(R.id.inventorylistview);
    		 	listView.setAdapter(null);
             
        	    TextView location = (TextView) header.findViewById(R.id.position);
        	
        	    
        	    databaseHelper.deleteAllData();
        	    StrictMode.setThreadPolicy(policy); 
                if(tipo==0){  LOCATION=CONT;   }
        		try{
    				
					String result = null;
		        	InputStream is = null;
		      
		        	String v1 = "'"+EMP+"'";
		    		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");

				String v2 = "'"+BOD+"'"; 
				String v3 = "'"+CONT+"'"; 

		        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/getInventoryPerLocation.php");
		        	        if(tipo==1){ httppost = new HttpPost("http://10.10.100.13/getInventoryPerItem.php");   }
		        	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        	        HttpResponse response = httpclient.execute(httppost); 
		        	        HttpEntity entity = response.getEntity();
		        	        is = entity.getContent();

		        	        Log.e("log_tag", "connection success ");
		        	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
		   	}
		   catch(Exception e)
		   	{
		        	        Log.e("log_tag", "Error in http connection "+e.toString());
		        	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
		        	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
		   	}
		        	//convert response to string
		   	try{
		   		
		        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
		        	        StringBuilder sb = new StringBuilder();
		        	        String line = null;
		        	        while ((line = reader.readLine()) != null) 
		        	        {
		        	                sb.append(line + "\n");
		        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
		        	        }
		        	        is.close();
		        	        result=sb.toString();
		   	}
		   	catch(Exception e)
		   	{
		        	       Log.e("log_tag", "Error converting result "+e.toString());
		       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
		   	}
		int counter=0;
		        	//parse json data
		        	try{

		        	 	JSONArray jArray = new JSONArray(result);
		        		for(int i=0;i<jArray.length();i++)  
			        {
		        			try{
		        		   	JSONObject no = jArray.getJSONObject(i);    
		        		    String loc=no.getString("Location");
		        		    String sku=no.getString("itemID");
		        			//String descripcion=   Normalizer.normalize(no.getString("Description"), Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
		        		    String qty=no.getString("qty");
		        		    try{
		        		    Double Qt = Double.parseDouble(qty);
		        		    NumberFormat nf = NumberFormat.getInstance();
			 	            nf.setMaximumFractionDigits(0);// set as you need
		        		    qty=nf.format(Qt).replace(",", "");
		        		    }catch(Exception e){}
		        		    String type=no.getString("dim");
		          		    String country=no.getString("country");
		          		    
		          		  String weight=no.getString("weight");
		        		    try{
			        		    Double Qt = Double.parseDouble(weight);
			        		    NumberFormat nf = NumberFormat.getInstance();
				 	            nf.setMaximumFractionDigits(8);// set as you need
				 	           weight=nf.format(Qt).replace(",", "");
			        		    }catch(Exception e){}
		 	                String volume=no.getString("vol");
		        		    try{
			        		    Double Qt = Double.parseDouble(volume);
			        		    NumberFormat nf = NumberFormat.getInstance();
				 	            nf.setMaximumFractionDigits(8);// set as you need
				 	           volume=nf.format(Qt).replace(",", "");
			        		    }catch(Exception e){}
		 	         
		 	                databaseHelper.saveInventoryLine(loc, sku, "", qty, type, country,weight,volume);
		 	                LOCATION=sku;    
		 	                if(tipo==0){  LOCATION=loc;   }
		 	                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.");
	        	}
        	    
        	    
        	    location.setText(LOCATION);
            	Cursor x =databaseHelper.getInventoryLines(LOCATION);
         	    if(tipo==1){x=databaseHelper.getInventoryItemLines(LOCATION);}
            	if(x.getCount()<=0){
            	if(tipo==0){
                Toast.makeText(getBaseContext(), "Ubicación no existente.", Toast.LENGTH_SHORT).show();}
            	else{
            	Toast.makeText(getBaseContext(), "Artículo no existente.", Toast.LENGTH_SHORT).show();	
            	}
                TextView Weight = (TextView) header.findViewById(R.id.weight);
                Weight.setText("Peso(g): 0");
                Typeface fontbold2 = Typeface.createFromAsset(context.getAssets(), "fonts/opensans-semibold.ttf"); 
                Weight.setTypeface(fontbold2);
                TextView Volume = (TextView) header.findViewById(R.id.volume);
                Volume.setText("Volumen(cm3): 0");
                Volume.setTypeface(fontbold2);
                location.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
            	}
            	else{
            	
                    double totalweight=0;double totalvolume=0;double locweight=0;double locvolume=0;
            		while (x.moveToNext()) {
            		double indqty=Double.parseDouble(x.getString(4));
            		totalweight=totalweight+indqty*Double.parseDouble(x.getString(7));
            		totalvolume=totalvolume+indqty*Double.parseDouble(x.getString(8));
            		}
            		NumberFormat nf = NumberFormat.getInstance();
                    nf.setMaximumFractionDigits(3);// set as you need
                    TextView Weight = (TextView) header.findViewById(R.id.weight);
                    Weight.setText("Peso(g): "+nf.format(totalweight));
                    Typeface fontbold2 = Typeface.createFromAsset(context.getAssets(), "fonts/opensans-semibold.ttf"); 
                    Weight.setTypeface(fontbold2);
                    TextView Volume = (TextView) header.findViewById(R.id.volume);
                    Volume.setText("Volumen(cm3): "+nf.format(totalvolume));
                    Volume.setTypeface(fontbold2);
                    location.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
            	}
            	
    		 	if(tipo==0){
    			 	newInventoryAdapter = new InventoryAdapter(context,databaseHelper.getInventoryLines(LOCATION));
    			 	}else if(tipo==1){
    			    newInventoryAdapter = new InventoryAdapter(context,databaseHelper.getInventoryItemLines(LOCATION)); 		
    			 	}
            	listView.setAdapter(newInventoryAdapter);
            	Scanning="";
		    }}
	 
			   
			}.start();  
 
        return super.onKeyDown(keyCode, event);
    }
    
	private void GetData() {
		
		//Receive data from bluetooth scanner
		Scanning="";
	
		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{
			 
				CONT=Scanning;
		    	databaseHelper = new InventoryDatabaseHelper(context); 
        	 	ListView listView = (ListView)findViewById(R.id.inventorylistview);
    		 	listView.setAdapter(null);
             
        	    TextView location = (TextView) header.findViewById(R.id.position);
        	
        	    
        	    databaseHelper.deleteAllData();
        	    StrictMode.setThreadPolicy(policy); 
                if(tipo==0){  LOCATION=CONT;   }
        		try{
    				
					String result = null;
		        	InputStream is = null;
		      
		        	String v1 = "'"+EMP+"'";
		    		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");

				String v2 = "'"+BOD+"'"; 
				String v3 = "'"+CONT+"'"; 

		        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/getInventoryPerLocation.php");
		        	        if(tipo==1){ httppost = new HttpPost("http://10.10.100.13/getInventoryPerItem.php");   }
		        	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        	        HttpResponse response = httpclient.execute(httppost); 
		        	        HttpEntity entity = response.getEntity();
		        	        is = entity.getContent();
		        	        Log.e("log_tag", "connection success ");
		        	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
		   	}
		   catch(Exception e)
		   	{
		        	        Log.e("log_tag", "Error in http connection "+e.toString());
		        	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
		        	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
		   	}
		        	//convert response to string
		   	try{
		   		
		        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
		        	        StringBuilder sb = new StringBuilder();
		        	        String line = null;
		        	        while ((line = reader.readLine()) != null) 
		        	        {
		        	                sb.append(line + "\n");
		        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
		        	        }
		        	        is.close();
		        	        result=sb.toString();
		   	}
		   	catch(Exception e)
		   	{
		        	       Log.e("log_tag", "Error converting result "+e.toString());
		       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
		   	}
		int counter=0;
		        	//parse json data
		        	try{

		        	 	JSONArray jArray = new JSONArray(result);
		        		for(int i=0;i<jArray.length();i++)  
			        {
		        			try{
		        		   	JSONObject no = jArray.getJSONObject(i);    
		        		    String loc=no.getString("Location");
		        		    String sku=no.getString("itemID");
		        			//String descripcion=   Normalizer.normalize(no.getString("Description"), Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
		        		    String qty=no.getString("qty");
		        		    try{
		        		    Double Qt = Double.parseDouble(qty);
		        		    NumberFormat nf = NumberFormat.getInstance();
			 	            nf.setMaximumFractionDigits(0);// set as you need
		        		    qty=nf.format(Qt).replace(",", "");
		        		    }catch(Exception e){}
		        		    String type=no.getString("dim");
		          		    String country=no.getString("country");
		          		    
		          		  String weight=no.getString("weight");
		        		    try{
			        		    Double Qt = Double.parseDouble(weight);
			        		    NumberFormat nf = NumberFormat.getInstance();
				 	            nf.setMaximumFractionDigits(8);// set as you need
				 	           weight=nf.format(Qt).replace(",", "");
			        		    }catch(Exception e){}
		 	                String volume=no.getString("vol");
		        		    try{
			        		    Double Qt = Double.parseDouble(volume);
			        		    NumberFormat nf = NumberFormat.getInstance();
				 	            nf.setMaximumFractionDigits(8);// set as you need
				 	           volume=nf.format(Qt).replace(",", "");
			        		    }catch(Exception e){}
		 	         
		 	                databaseHelper.saveInventoryLine(loc, sku, "", qty, type, country,weight,volume);
		 	                LOCATION=sku;    
		 	                if(tipo==0){  LOCATION=loc;   }
		 	                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.");
	        	}
        	    
        	    
        	    location.setText(LOCATION);
            	Cursor x =databaseHelper.getInventoryLines(LOCATION);
         	    if(tipo==1){x=databaseHelper.getInventoryItemLines(LOCATION);}
            	if(x.getCount()<=0){
            	if(tipo==0){
                Toast.makeText(getBaseContext(), "Ubicación no existente.", Toast.LENGTH_SHORT).show();}
            	else{
            	Toast.makeText(getBaseContext(), "Artículo no existente.", Toast.LENGTH_SHORT).show();	
            	}
                TextView Weight = (TextView) header.findViewById(R.id.weight);
                Weight.setText("Peso(g): 0");
                Typeface fontbold2 = Typeface.createFromAsset(context.getAssets(), "fonts/opensans-semibold.ttf"); 
                Weight.setTypeface(fontbold2);
                TextView Volume = (TextView) header.findViewById(R.id.volume);
                Volume.setText("Volumen(cm3): 0");
                Volume.setTypeface(fontbold2);
                location.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
            	}
            	else{
            	
                    double totalweight=0;double totalvolume=0;double locweight=0;double locvolume=0;
            		while (x.moveToNext()) {
            		double indqty=Double.parseDouble(x.getString(4));
            		totalweight=totalweight+indqty*Double.parseDouble(x.getString(7));
            		totalvolume=totalvolume+indqty*Double.parseDouble(x.getString(8));
            		}
            		NumberFormat nf = NumberFormat.getInstance();
                    nf.setMaximumFractionDigits(3);// set as you need
                    TextView Weight = (TextView) header.findViewById(R.id.weight);
                    Weight.setText("Peso(g): "+nf.format(totalweight));
                    Typeface fontbold2 = Typeface.createFromAsset(context.getAssets(), "fonts/opensans-semibold.ttf"); 
                    Weight.setTypeface(fontbold2);
                    TextView Volume = (TextView) header.findViewById(R.id.volume);
                    Volume.setText("Volumen(cm3): "+nf.format(totalvolume));
                    Volume.setTypeface(fontbold2);
                    location.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
            	}
            	
    		 	if(tipo==0){
    			 	newInventoryAdapter = new InventoryAdapter(context,databaseHelper.getInventoryLines(LOCATION));
    			 	}else if(tipo==1){
    			    newInventoryAdapter = new InventoryAdapter(context,databaseHelper.getInventoryItemLines(LOCATION)); 		
    			 	}
            	listView.setAdapter(newInventoryAdapter);
				
				
				
                timerstarted=0;
	      	      Scanning="";
	      	      timercompleted=false;
				
			}
						}
		}}.start();  
}
			
			}	
		});

	}
 
 
    
    

}
