/*
 * 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.Picking;


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 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.example.waoperations.R;


import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import android.widget.LinearLayout;
import android.widget.ListView;

import android.widget.TextView;
import android.widget.Toast;

/**
 * Main UI for the  app.
 */
public class PickingSummary extends Activity {
	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	public String BOD,EMP,PO,USER,EQUIPO,USERCODE,REVERSE;
	public int INDEX;
    TextView mDisplay;
    PickingAdapter newPickingAdapter;
    private ProgressDialog progressDialog;
    private SwipeRefreshLayout swipeRefreshLayout;
    private PickingDatabaseHelper databaseHelper;
    //private static final String TAG = "DemoActivity";
    
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pickinglist);
        View header = getLayoutInflater().inflate(R.layout.generalheader, null);
        TextView HeaderName = (TextView) header.findViewById(R.id.tableroheader);
		Intent intent = getIntent();
		PO=intent.getStringExtra("PO");
		EMP=intent.getStringExtra("EMP");
		BOD=intent.getStringExtra("BOD");
		USER=intent.getStringExtra("USER");	
		USERCODE=intent.getStringExtra("USERCODE");	
		EQUIPO=intent.getStringExtra("EQUIPO");	
		REVERSE=intent.getStringExtra("REVERSE");	
        HeaderName.setText("PICK : "+PO);
	    ListView listView = (ListView)findViewById(R.id.pickinglistview);
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    
	    actionBar.setSubtitle("Picking");
	    actionBar.setTitle("Warehouse");
	    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
	    actionBar.setDisplayShowTitleEnabled(false);  // required to force redraw, without, gray color
	    actionBar.setDisplayShowTitleEnabled(true);
	    actionBar.setDisplayHomeAsUpEnabled(false);
	    actionBar.show(); 

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

	    newPickingAdapter = new PickingAdapter(this.getApplicationContext(),databaseHelper.getAllPickLines(PO));
  	    listView.setAdapter(newPickingAdapter);
  	

  	    OnItemClickListener itemClickListener = new OnItemClickListener() {
         @Override
         public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
            // Getting the Container Layout of the ListView
            LinearLayout linearLayoutParent = (LinearLayout) container;
            linearLayoutParent.setBackgroundColor(getResources().getColor(R.color.SkyBlue));
            // Getting the inner Linear Layout
            LinearLayout linearLayoutChild = (LinearLayout) linearLayoutParent.getChildAt(0);
            //Getting the Country TextView
            TextView loc = (TextView) linearLayoutChild.getChildAt(0);
            TextView sku = (TextView) linearLayoutChild.getChildAt(1);
           	Intent intento = new Intent(getApplicationContext() ,PickingDetail.class);
         	//intento.putExtra("PO", PO);
     	    intento.putExtra("EX","1"); 
     	    intento.putExtra("INVENDIMID",position+""); 
     		intento.putExtra("PO", PO);
      	    intento.putExtra("DATA",EMP); 
      	    intento.putExtra("USER",USER); 
    	 	ListView listView = (ListView)findViewById(R.id.pickinglistview);
      	    INDEX = listView.getFirstVisiblePosition();
      
     	    startActivity(intento);
     	     linearLayoutParent.setBackgroundColor(getResources().getColor(R.color.white));
             //Toast.makeText(getBaseContext(), tvCountry.getText().toString(), Toast.LENGTH_SHORT).show();
         }
     };
     // Setting the item click listener for the listview
     listView.setOnItemClickListener(itemClickListener);

     }
    
    
    
    private class LoadViewTask extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  
        @Override  
        protected void onPreExecute()  
        {  
        	progressDialog = ProgressDialog.show(PickingSummary.this,"Cargando...",  
        		    "Cargando información, favor espere...", false, false);
        }  
  
        //The code to be executed in a background thread.  
        @Override  
        protected Void doInBackground(Void... params)  
        {  
            /* This is just a code that delays the thread execution 4 times, 
             * during 850 milliseconds and updates the current progress. This 
             * is where the code that is going to be executed on a background 
             * thread must be placed. 
             */  
        	 StrictMode.setThreadPolicy(policy); 
     	    
     		try{
     			
     			String result = null;
     	    	InputStream is = null;
     	  
     	    	String v1 = "'"+EMP+"'";
     			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");


     		String v2 = "'"+BOD+"'"; 
     		String v3 = "'"+PO+"'"; 
     		String v4 = "'"+EQUIPO+"'"; 

     	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     	     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
     	      	nameValuePairs.add(new BasicNameValuePair("bodega",v2));
     	    	nameValuePairs.add(new BasicNameValuePair("id",v3));
     	    	nameValuePairs.add(new BasicNameValuePair("equipo",v4));
     	    	
     	//apartir de aqui carga ruta
     		try
     		{
     	    	        HttpClient httpclient = new DefaultHttpClient();
     	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/getPickingList.php");
     	    	        if(REVERSE.equals("1")){
     	    	        httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/getPickingListReverse.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 po=no.getString("UID");
     	    		    PO=po;
     	    		    String loc=no.getString("location").trim();
     	    		    String sku=no.getString("itemID");
     	    		    
     	    			String descripcion=   Normalizer.normalize(no.getString("Description"), Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
     	    		    String qty=no.getString("qty");
     	    		    String factor=no.getString("factor");
     	    		    
     	    		    double receiveamount=0;
     	    		    try{
     	        		    Double Qt = Double.parseDouble(qty);
     	        		    receiveamount=Qt;
     	        		    NumberFormat nf = NumberFormat.getInstance();
     		 	            nf.setMaximumFractionDigits(0);// set as you need
     	        		    qty=nf.format(Qt).replace(",", "");
     	        		    }catch(Exception e){}
     	    		    
     	    		    double unitconv=0;
     	    		    try{
     	        		    Double unit = Double.parseDouble(factor);
     	        		    unitconv=unit;
     	        		    NumberFormat nf = NumberFormat.getInstance();
     		 	            nf.setMaximumFractionDigits(0);// set as you need
     	        		    factor=nf.format(unit).replace(",", "");
     	        		    }catch(Exception e){}
         		    
         		    if(unitconv>0){
         		    	receiveamount=receiveamount*unitconv;
         		    	  NumberFormat nf = NumberFormat.getInstance();
         		    	   qty=nf.format(receiveamount).replace(",", "");
         		    }

     	    		    String type=no.getString("type");
     	    		   if(factor.equals("null")){
               	        type="und";  
               	        }
     	      		    String country=no.getString("country");
     	      		    String barcode=no.getString("barcode");
     	      		  String ORDERID=no.getString("ORDERID");
     	      		  String ROUTEID=no.getString("ROUTEID");
     	      		  String INVENTRANSID=no.getString("INVENTRANSID");
     	      		  String INVENTDIMID=no.getString("INVENTDIMID");
     	      
     		            NumberFormat nf = NumberFormat.getInstance();
     		            nf.setMaximumFractionDigits(0);// set as you need
                         databaseHelper.savePickLine(po,loc,sku,descripcion,qty,type,"0","0",barcode,country,ORDERID,ROUTEID,INVENTRANSID,INVENTDIMID,"0");

     		                counter++;
     		   
     	    			}catch(Exception e)
     		          	{
     	    			  
     		          	}
     		       }
     	  
     	    	}
     	    	catch(JSONException e)
     	    	{
     	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
              	} catch (IllegalArgumentException e) {
     				// TODO Auto-generated catch block
     				e.printStackTrace();
     			} 	
     			}catch(Exception e)
     	    	{

     		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
     		}

     	Cursor x =databaseHelper.getAllPickLines(PO);
     	if(x.getCount()==0){
    //     Toast.makeText(getBaseContext(), "No hay líneas asociadas.", Toast.LENGTH_LONG).show();	
     	}else{
     try{
     			
     			String result = null;
     	    	InputStream is = null;
     	  
     	    	String v1 = "'"+EMP+"'";
     			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");


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

     	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     	     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
     	    	nameValuePairs.add(new BasicNameValuePair("UID",v3));
     	    	
     	//apartir de aqui carga ruta
     		try
     		{
     	    	        HttpClient httpclient = new DefaultHttpClient();
     	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/getPickingNotProcessedList.php");
     	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     	    	        HttpResponse response = httpclient.execute(httppost); 
     	    	        HttpEntity entity = response.getEntity();
     	    	        is = entity.getContent();

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

     	    	 	JSONArray jArray = new JSONArray(result);
     	    		for(int i=0;i<jArray.length();i++)  
     	            {
     	    			try{
     	    		   	JSONObject no = jArray.getJSONObject(i);

     	    	        String COUNTED=no.getString("COUNTED");
     	    	        String orderid=no.getString("ORDERID");
     	    
     	    	        double receiveamount=0;
     	    		    try{
     	        		    Double Qt = Double.parseDouble(COUNTED);
     	        		    receiveamount=Qt;
     	        		    NumberFormat nf = NumberFormat.getInstance();
     		 	            nf.setMaximumFractionDigits(0);// set as you need
     		 	        COUNTED=nf.format(Qt).replace(",", "");
     	        		    
     	        		}catch(Exception e){}
     	      		    String itrans=no.getString("INVENTDIMID");
     	      		    String itemid=no.getString("ITEMID");
     		            NumberFormat nf = NumberFormat.getInstance();
     		            nf.setMaximumFractionDigits(0);// set as you need
     		        	Cursor xyz =databaseHelper.getItemDetail(PO,itrans,itemid,orderid);
     		    		if(xyz.getCount()>0){
     		    		xyz.moveToFirst();
     	                databaseHelper.UpdateScannedItem(COUNTED, xyz.getString(0));
     	                }
     		            counter++;
     	    			}catch(Exception e)
     		          	{
     		          	}
     		            	 }
     	  
     	    	}
     	    	catch(JSONException e)
     	    	{
     	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
     	     	} catch (IllegalArgumentException e) {
     				// TODO Auto-generated catch block
     				e.printStackTrace();
     			} 	
     			}catch(Exception e)
     	    	{
     		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
     		}

     
     
 	Cursor Y =databaseHelper.getAllPickLines(PO);
 	if(Y.getCount()==0){
//     Toast.makeText(getBaseContext(), "No hay líneas asociadas.", Toast.LENGTH_LONG).show();	
 	}else{
 try{
 			
 			String result = null;
 	    	InputStream is = null;
 	  
 	    	String v1 = "'"+EMP+"'";
 			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");


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

 	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 	     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
 	    	nameValuePairs.add(new BasicNameValuePair("bodega",v2));
 	    	
 	//apartir de aqui carga ruta
 		try
 		{
 	    	        HttpClient httpclient = new DefaultHttpClient();
 	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/getReplenishmentList.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 itemid=no.getString("ITEMID");
 	      		    String position=no.getString("TOLOCATION");

 	      		    
 		        	Cursor xyz =databaseHelper.getItemPosition(PO,itemid,position);
 		    		if(xyz.getCount()>0){
 		    		xyz.moveToFirst();
 	                databaseHelper.UpdateReplenishmentPending(xyz.getString(0));
 	                }
 		            counter++;
 	    			}catch(Exception e)
 		          	{
 		          	}
 		            	 }
 	  
 	    	}
 	    	catch(JSONException e)
 	    	{
 	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
 	     	} catch (IllegalArgumentException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			} 	
 			}catch(Exception e)
 	    	{
 		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
 		}
 	}
     
     
     
     		try{
     		 	 String result = null;
     		 	InputStream is = null;
     		 	String v1 = "'"+USER+"'";
     			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
     			SimpleDateFormat sdfc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     			String v2 = "'"+sdfa.format(new Date())+"'"; 
     			
     		    String ingreso = "'"+sdfc.format(new Date())+"'"; 
     		 	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     		 	
     		 	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
     			String dat = sd.format(new Date())+"-01"; 
     		  	nameValuePairs.add(new BasicNameValuePair("UserCode",v1));
     		 	nameValuePairs.add(new BasicNameValuePair("Motive","'30'"));
     		    nameValuePairs.add(new BasicNameValuePair("UID","'"+PO+"'"));
     		  	nameValuePairs.add(new BasicNameValuePair("Date",ingreso));
     		    nameValuePairs.add(new BasicNameValuePair("Warehouse","'"+BOD+"'"));
     		    nameValuePairs.add(new BasicNameValuePair("Company","'"+EMP+"'"));
     		    nameValuePairs.add(new BasicNameValuePair("Lines","'"+x.getCount()+"'"));
     		    StrictMode.setThreadPolicy(policy); 
     		        	//http post
     		        	try{
     		        	        HttpClient httpclient = new DefaultHttpClient();
     		        	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/insertUserLogWAN.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(), "Error de conexión", Toast.LENGTH_SHORT).show();
     		        	}
     		        	//convert response to string
     		        	try{
     		        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
     		        	        StringBuilder sb = new StringBuilder();
     		        	        String line = null;
     		        	        while ((line = reader.readLine()) != null) 
     		        	        {
     		        	                sb.append(line + "\n");
     		        	        }
     		        	        is.close();

     		        	        result=sb.toString();
     		        	}
     		        	catch(Exception e)
     		        	{
     		        	       Log.e("log_tag", "Error converting result "+e.toString());
     		           	}
     		        	try{
     		        	            	//JSONObject json_data = new JSONObject(result);
     		        	          	String rb=result;
     		        	             //   CharSequence w= (CharSequence) json_data.get("re");
     		        	  			 //   Toast toasta=Toast.makeText(getApplicationContext(), w, 2000);
     						  	    //    toasta.setGravity(Gravity.CENTER,0,0);
     						  	     //   toasta.show();	
     		        	     }
     		        	catch(Exception e)
     		        	   {
     		        	        Log.e("log_tag", "Error parsing data "+e.toString());
     		        	  //      Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
     		        	    }}catch(Exception e){}
     		
     	}
      	
     
            return null;  
        }  
  
        //Update the progress  
        @Override  
        protected void onProgressUpdate(Integer... values)  
        {  
            //set the current progress of the progress dialog  
            progressDialog.setProgress(values[0]);  
  
        }  
  
        //after executing the code in the thread  
        @Override  
        protected void onPostExecute(Void result)  
        {  
            //close the progress dialog  
            progressDialog.dismiss();  
            //initialize the View  
            setContentView(R.layout.pickinglist);
            View header = getLayoutInflater().inflate(R.layout.generalheader, null);
            TextView HeaderName = (TextView) header.findViewById(R.id.tableroheader);
    		Intent intent = getIntent();
    		PO=intent.getStringExtra("PO");
    		EMP=intent.getStringExtra("EMP");
    		BOD=intent.getStringExtra("BOD");
    		USER=intent.getStringExtra("USER");	
    		USERCODE=intent.getStringExtra("USERCODE");	
    		EQUIPO=intent.getStringExtra("EQUIPO");	
    		
            HeaderName.setText("PICK : "+PO);
    	    ListView listView = (ListView)findViewById(R.id.pickinglistview);
    		

    	    ActionBar actionBar = getActionBar();
    	    actionBar.hide();
    	    // more stuff here...
    	    
    	    actionBar.setSubtitle("Picking");
    	    actionBar.setTitle("Warehouse");
    	    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
    	    actionBar.setDisplayShowTitleEnabled(false);  // required to force redraw, without, gray color
    	    actionBar.setDisplayShowTitleEnabled(true);
    	    actionBar.setDisplayHomeAsUpEnabled(false);
    	    actionBar.show(); 

            Typeface fontbold = Typeface.createFromAsset(PickingSummary.this.getAssets(), "fonts/opensans-extrabold.ttf"); 
    	    HeaderName.setTypeface(fontbold);
    	    listView.addHeaderView(header);
        	listView.setAdapter(newPickingAdapter);
    	    listView.setCacheColorHint(Color.TRANSPARENT);
    		listView.setAdapter(null);
    	
    		  swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    			swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    			      @Override
    			      public void onRefresh() {
    			    		databaseHelper.deleteAllData();
    			    	  new LoadViewTaskRefresh().execute();        
    			        
    			  }});
    		
    			swipeRefreshLayout.setColorScheme(
    					   R.color.Gray, R.color.green, R.color.ForestGreen,R.color.Cyan);
        
    		
    		
    	newPickingAdapter = new PickingAdapter(PickingSummary.this,databaseHelper.getAllPickLines(PO));
      	listView.setAdapter(newPickingAdapter);
    	listView.setCacheColorHint(Color.TRANSPARENT);
      
    	OnItemClickListener itemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
                // Getting the Container Layout of the ListView
                LinearLayout linearLayoutParent = (LinearLayout) container;
                linearLayoutParent.setBackgroundColor(getResources().getColor(R.color.SkyBlue));
                // Getting the inner Linear Layout
                LinearLayout linearLayoutChild = (LinearLayout) linearLayoutParent.getChildAt(0);
                //Getting the Country TextView
                TextView loc = (TextView) linearLayoutChild.getChildAt(0);
                TextView sku = (TextView) linearLayoutChild.getChildAt(1);
              	Intent intento = new Intent(getApplicationContext() ,PickingDetail.class);
            	//intento.putExtra("PO", PO);
        	    intento.putExtra("EX","1"); 
        	    intento.putExtra("INVENDIMID",position+""); 
        		intento.putExtra("PO", PO);
         	    intento.putExtra("DATA",EMP); 
         	    intento.putExtra("USER",USER); 
         		ListView listView = (ListView)findViewById(R.id.pickinglistview);
          	    INDEX = listView.getFirstVisiblePosition();
        	    startActivity(intento);
        	     linearLayoutParent.setBackgroundColor(getResources().getColor(R.color.white));
                //Toast.makeText(getBaseContext(), tvCountry.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        };
        // Setting the item click listener for the listview
        listView.setOnItemClickListener(itemClickListener);

        }
        
      
    
    }
  

    private class LoadViewTaskRefresh extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  
        @Override  
        protected void onPreExecute()  
        {  
        //	progressDialog = ProgressDialog.show(PickingSummary.this,"Cargando...",  
        //		    "Cargando información, favor espere...", false, false);
        }  
  
        //The code to be executed in a background thread.  
        @Override  
        protected Void doInBackground(Void... params)  
        {  
            /* This is just a code that delays the thread execution 4 times, 
             * during 850 milliseconds and updates the current progress. This 
             * is where the code that is going to be executed on a background 
             * thread must be placed. 
             */  
        	 StrictMode.setThreadPolicy(policy); 
     	    
     		try{
     			
     			String result = null;
     	    	InputStream is = null;
     	  
     	    	String v1 = "'"+EMP+"'";
     			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");


     		String v2 = "'"+BOD+"'"; 
     		String v3 = "'"+PO+"'"; 
     		String v4 = "'"+EQUIPO+"'"; 

     	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     	     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
     	      	nameValuePairs.add(new BasicNameValuePair("bodega",v2));
     	    	nameValuePairs.add(new BasicNameValuePair("id",v3));
     	    	nameValuePairs.add(new BasicNameValuePair("equipo",v4));
     	    	
     	//apartir de aqui carga ruta
     		try
     		{
     		     HttpClient httpclient = new DefaultHttpClient();
	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/getPickingList.php");
	    	        if(REVERSE.equals("1")){
	    	        httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/getPickingListReverse.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 po=no.getString("UID");
     	    		    PO=po;
     	    		    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");
     	    		    String factor=no.getString("factor");
     	    		    
     	    		    double receiveamount=0;
     	    		    try{
     	        		    Double Qt = Double.parseDouble(qty);
     	        		    receiveamount=Qt;
     	        		    NumberFormat nf = NumberFormat.getInstance();
     		 	            nf.setMaximumFractionDigits(0);// set as you need
     	        		    qty=nf.format(Qt).replace(",", "");
     	        		    }catch(Exception e){}
     	    		    
     	    		    double unitconv=0;
     	    		    try{
     	        		    Double unit = Double.parseDouble(factor);
     	        		    unitconv=unit;
     	        		    NumberFormat nf = NumberFormat.getInstance();
     		 	            nf.setMaximumFractionDigits(0);// set as you need
     	        		    factor=nf.format(unit).replace(",", "");
     	        		    }catch(Exception e){}
         		    
         		    if(unitconv>0){
         		    	receiveamount=receiveamount*unitconv;
         		    	  NumberFormat nf = NumberFormat.getInstance();
         		    	   qty=nf.format(receiveamount).replace(",", "");
         		    }
     	    		    
     	    		    
     	    		    
     	    		    
     	    		    String type=no.getString("type");
     	    		   if(factor.equals("null")){
               	        type="und";  
               	        }
     	      		    String country=no.getString("country");
     	      		    String barcode=no.getString("barcode");
     	      		  String ORDERID=no.getString("ORDERID");
     	      		  String ROUTEID=no.getString("ROUTEID");
     	      		  String INVENTRANSID=no.getString("INVENTRANSID");
     	      		  String INVENTDIMID=no.getString("INVENTDIMID");
     	      
     		            NumberFormat nf = NumberFormat.getInstance();
     		            nf.setMaximumFractionDigits(0);// set as you need
                         databaseHelper.savePickLine(po,loc,sku,descripcion,qty,type,"0","0",barcode,country,ORDERID,ROUTEID,INVENTRANSID,INVENTDIMID,"0");

     		                counter++;
     		   
     	    			}catch(Exception e)
     		          	{
     	    			  
     		          	}
     		            	 }
     	  
     	    	}
     	    	catch(JSONException e)
     	    	{
     	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
              	} catch (IllegalArgumentException e) {
     				// TODO Auto-generated catch block
     				e.printStackTrace();
     			} 	
     			}catch(Exception e)
     	    	{

     		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
     		}

     	Cursor x =databaseHelper.getAllPickLines(PO);
     	if(x.getCount()==0){
    //     Toast.makeText(getBaseContext(), "No hay líneas asociadas.", Toast.LENGTH_LONG).show();	
     	}else{
     try{
     			
     			String result = null;
     	    	InputStream is = null;
     	  
     	    	String v1 = "'"+EMP+"'";
     			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
     			String v2 = "'"+BOD+"'"; 
     			String v3 = "'"+PO+"'"; 

     	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     	     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
     	    	nameValuePairs.add(new BasicNameValuePair("UID",v3));
     	    	
     	//apartir de aqui carga ruta
     		try
     		{
     	    	        HttpClient httpclient = new DefaultHttpClient();
     	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/getPickingNotProcessedList.php");
     	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     	    	        HttpResponse response = httpclient.execute(httppost); 
     	    	        HttpEntity entity = response.getEntity();
     	    	        is = entity.getContent();

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

     	    	 	JSONArray jArray = new JSONArray(result);
     	    		for(int i=0;i<jArray.length();i++)  
     	            {
     	    			try{
     	    		   	JSONObject no = jArray.getJSONObject(i);

     	    	        String COUNTED=no.getString("COUNTED");
     	    	        String orderid=no.getString("ORDERID");
     	    
     	    	        double receiveamount=0;
     	    		    try{
     	        		    Double Qt = Double.parseDouble(COUNTED);
     	        		    receiveamount=Qt;
     	        		    NumberFormat nf = NumberFormat.getInstance();
     		 	            nf.setMaximumFractionDigits(0);// set as you need
     		 	        COUNTED=nf.format(Qt).replace(",", "");
     	        		    
     	        		}catch(Exception e){}
     	      		    String itrans=no.getString("INVENTDIMID");
     	      		    String itemid=no.getString("ITEMID");
     		            NumberFormat nf = NumberFormat.getInstance();
     		            nf.setMaximumFractionDigits(0);// set as you need
     		        	Cursor xyz =databaseHelper.getItemDetail(PO,itrans,itemid,orderid);
     		    		if(xyz.getCount()>0){
     		    		xyz.moveToFirst();
     	                databaseHelper.UpdateScannedItem(COUNTED, xyz.getString(0));
     	                }
     		            counter++;
     	    			}catch(Exception e)
     		          	{
     		          	}
     		            	 }
     	  
     	    	}
     	    	catch(JSONException e)
     	    	{
     	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
     	     	} catch (IllegalArgumentException e) {
     				// TODO Auto-generated catch block
     				e.printStackTrace();
     			} 	
     			}catch(Exception e)
     	    	{
     		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
     		}

     
 	Cursor Y =databaseHelper.getAllPickLines(PO);
 	if(Y.getCount()==0){
//     Toast.makeText(getBaseContext(), "No hay líneas asociadas.", Toast.LENGTH_LONG).show();	
 	}else{
 try{
 			
 			String result = null;
 	    	InputStream is = null;
 	  
 	    	String v1 = "'"+EMP+"'";
 			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
 			String v2 = "'"+BOD+"'"; 
 			String v3 = "'"+PO+"'"; 

 	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 	     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
 	    	nameValuePairs.add(new BasicNameValuePair("bodega",v2));
 	    	
 	//apartir de aqui carga ruta
 		try
 		{
 	    	        HttpClient httpclient = new DefaultHttpClient();
 	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/getReplenishmentList.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 itemid=no.getString("ITEMID");
 	      		    String position=no.getString("TOLOCATION");

 	      		    
 		        	Cursor xyz =databaseHelper.getItemPosition(PO,itemid,position);
 		    		if(xyz.getCount()>0){
 		    		xyz.moveToFirst();
 	                databaseHelper.UpdateReplenishmentPending(xyz.getString(0));
 	                }
 		            counter++;
 	    			}catch(Exception e)
 		          	{
 		          	}
 		            	 }
 	  
 	    	}
 	    	catch(JSONException e)
 	    	{
 	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
 	     	} catch (IllegalArgumentException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			} 	
 			}catch(Exception e)
 	    	{
 		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
 		}
 	}
     
     
     		try{
     		 	 String result = null;
     		 	InputStream is = null;
     		 	String v1 = "'"+USER+"'";
     			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
     			SimpleDateFormat sdfc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     			String v2 = "'"+sdfa.format(new Date())+"'"; 
     			
     		    String ingreso = "'"+sdfc.format(new Date())+"'"; 
     		 	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     		 	
     		 	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
     			String dat = sd.format(new Date())+"-01"; 
     		  	nameValuePairs.add(new BasicNameValuePair("UserCode",v1));
     		 	nameValuePairs.add(new BasicNameValuePair("Motive","'30'"));
     		    nameValuePairs.add(new BasicNameValuePair("UID","'"+PO+"'"));
     		  	nameValuePairs.add(new BasicNameValuePair("Date",ingreso));
     		    nameValuePairs.add(new BasicNameValuePair("Warehouse","'"+BOD+"'"));
     		    nameValuePairs.add(new BasicNameValuePair("Company","'"+EMP+"'"));
     		    nameValuePairs.add(new BasicNameValuePair("Lines","'"+x.getCount()+"'"));
     		    StrictMode.setThreadPolicy(policy); 
     		        	//http post
     		        	try{
     		        	        HttpClient httpclient = new DefaultHttpClient();
     		        	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/insertUserLogWAN.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(), "Error de conexión", Toast.LENGTH_SHORT).show();
     		        	}
     		        	//convert response to string
     		        	try{
     		        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
     		        	        StringBuilder sb = new StringBuilder();
     		        	        String line = null;
     		        	        while ((line = reader.readLine()) != null) 
     		        	        {
     		        	                sb.append(line + "\n");
     		        	        }
     		        	        is.close();

     		        	        result=sb.toString();
     		        	}
     		        	catch(Exception e)
     		        	{
     		        	       Log.e("log_tag", "Error converting result "+e.toString());
     		           	}
     		        	try{
     		        	            	//JSONObject json_data = new JSONObject(result);
     		        	          	String rb=result;
     		        	             //   CharSequence w= (CharSequence) json_data.get("re");
     		        	  			 //   Toast toasta=Toast.makeText(getApplicationContext(), w, 2000);
     						  	    //    toasta.setGravity(Gravity.CENTER,0,0);
     						  	     //   toasta.show();	
     		        	     }
     		        	catch(Exception e)
     		        	   {
     		        	        Log.e("log_tag", "Error parsing data "+e.toString());
     		        	   //     Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
     		        	    }}catch(Exception e){}
     		
     	}
      	
     
            return null;  
        }  
  
        //Update the progress  
        @Override  
        protected void onProgressUpdate(Integer... values)  
        {  
            //set the current progress of the progress dialog  
            progressDialog.setProgress(values[0]);  
  
        }  
  
        //after executing the code in the thread  
        @Override  
        protected void onPostExecute(Void result)  
        {  
            //close the progress dialog  
            progressDialog.dismiss();  
            //initialize the View  
            setContentView(R.layout.pickinglist);
            View header = getLayoutInflater().inflate(R.layout.generalheader, null);
            TextView HeaderName = (TextView) header.findViewById(R.id.tableroheader);
    		Intent intent = getIntent();
    		PO=intent.getStringExtra("PO");
    		EMP=intent.getStringExtra("EMP");
    		BOD=intent.getStringExtra("BOD");
    		USER=intent.getStringExtra("USER");	
    		USERCODE=intent.getStringExtra("USERCODE");	
    		EQUIPO=intent.getStringExtra("EQUIPO");	
    		
            HeaderName.setText("PICK : "+PO);
    	    ListView listView = (ListView)findViewById(R.id.pickinglistview);
    		

    	    ActionBar actionBar = getActionBar();
    	    actionBar.hide();
    	    // more stuff here...
    	    
    	    actionBar.setSubtitle("Picking");
    	    actionBar.setTitle("Warehouse");
    	    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
    	    actionBar.setDisplayShowTitleEnabled(false);  // required to force redraw, without, gray color
    	    actionBar.setDisplayShowTitleEnabled(true);
    	    actionBar.setDisplayHomeAsUpEnabled(false);
    	    actionBar.show(); 

            Typeface fontbold = Typeface.createFromAsset(PickingSummary.this.getAssets(), "fonts/opensans-extrabold.ttf"); 
    	    HeaderName.setTypeface(fontbold);
    	    listView.addHeaderView(header);
        	listView.setAdapter(newPickingAdapter);
    	    listView.setCacheColorHint(Color.TRANSPARENT);
    		listView.setAdapter(null);
    	
    		swipeRefreshLayout.setRefreshing(false);
    		  swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    			swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    			      @Override
    			      public void onRefresh() {
    			    		databaseHelper.deleteAllData();
    			    	  new LoadViewTaskRefresh().execute();        
    			        
    			  }});
    		
    			swipeRefreshLayout.setColorScheme(
    					   R.color.Gray, R.color.green, R.color.ForestGreen,R.color.Cyan);
        
    		
    		
    	newPickingAdapter = new PickingAdapter(PickingSummary.this,databaseHelper.getAllPickLines(PO));
      	listView.setAdapter(newPickingAdapter);
    	listView.setCacheColorHint(Color.TRANSPARENT);
      
    	OnItemClickListener itemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
                // Getting the Container Layout of the ListView
                LinearLayout linearLayoutParent = (LinearLayout) container;
                linearLayoutParent.setBackgroundColor(getResources().getColor(R.color.SkyBlue));
                // Getting the inner Linear Layout
                LinearLayout linearLayoutChild = (LinearLayout) linearLayoutParent.getChildAt(0);
                //Getting the Country TextView
                TextView loc = (TextView) linearLayoutChild.getChildAt(0);
                TextView sku = (TextView) linearLayoutChild.getChildAt(1);
              	Intent intento = new Intent(getApplicationContext() ,PickingDetail.class);
            	//intento.putExtra("PO", PO);
        	    intento.putExtra("EX","1"); 
        	    intento.putExtra("INVENDIMID",position+""); 
        		intento.putExtra("PO", PO);
         	    intento.putExtra("DATA",EMP); 
         	    intento.putExtra("USER",USER); 
         		ListView listView = (ListView)findViewById(R.id.pickinglistview);
          	    INDEX = listView.getFirstVisiblePosition();
        	    startActivity(intento);
        	     linearLayoutParent.setBackgroundColor(getResources().getColor(R.color.white));
                //Toast.makeText(getBaseContext(), tvCountry.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        };
        // Setting the item click listener for the listview
        listView.setOnItemClickListener(itemClickListener);

        }
        
      
    
    }
  
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.newpickpath, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.pickpath:
            	
            	Intent intento = new Intent(getApplicationContext() ,PickingDetail.class);
            	intento.putExtra("PO", PO);
           	    intento.putExtra("EX","0"); 
          	    intento.putExtra("DATA",EMP); 
          	    intento.putExtra("USER",USER); 
        	 	ListView listView = (ListView)findViewById(R.id.pickinglistview);
          	    INDEX = listView.getFirstVisiblePosition();
        	    startActivity(intento);
                return true;
       
   case R.id.upload:
            	
        		AlertDialog.Builder builder = new AlertDialog.Builder(this);
        		builder.setMessage("¿Desea terminar el alisto?")
        		   .setCancelable(false)
        		   .setPositiveButton("Sí", new DialogInterface.OnClickListener() {
        		       public void onClick(DialogInterface dialog, int id) {
        		 
        		    		try{
        		   		 	 String result = null;
        		   		 	InputStream is = null;
        		   		 	String v1 = "'"+USER+"'";
        		   			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
        		   			SimpleDateFormat sdfc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        		   			String v2 = "'"+sdfa.format(new Date())+"'"; 
        		   			
        		   		    String ingreso = "'"+sdfc.format(new Date())+"'"; 
        		   		 	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        		   		 	
        		   		 	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
        		   			String dat = sd.format(new Date())+"-01"; 

        		   		  	nameValuePairs.add(new BasicNameValuePair("UserCode",v1));
        		   		 	nameValuePairs.add(new BasicNameValuePair("Motive","'31'"));
        		   		    nameValuePairs.add(new BasicNameValuePair("UID","'"+PO+"'"));
        		   		  	nameValuePairs.add(new BasicNameValuePair("Date",ingreso));
        		   		    nameValuePairs.add(new BasicNameValuePair("Warehouse","'"+BOD+"'"));
        		   		    nameValuePairs.add(new BasicNameValuePair("Company","'"+EMP+"'"));

        		   		  		
        		   		    StrictMode.setThreadPolicy(policy); 
        		   		        	//http post
        		   		        	try{
        		   		        	        HttpClient httpclient = new DefaultHttpClient();
        		   		        	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Picking/insertUserLogWAN.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(), "Error de conexión", Toast.LENGTH_SHORT).show();

        		   		        	}
        		   		        	//convert response to string
        		   		        	try{
        		   		        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        		   		        	        StringBuilder sb = new StringBuilder();
        		   		        	        String line = null;
        		   		        	        while ((line = reader.readLine()) != null) 
        		   		        	        {
        		   		        	                sb.append(line + "\n");
        		   		        	        }
        		   		        	        is.close();

        		   		        	        result=sb.toString();
        		   		        	}
        		   		        	catch(Exception e)
        		   		        	{
        		   		        	       Log.e("log_tag", "Error converting result "+e.toString());
        		   		           	}
        		   		        	try{
        		   		        	            	String resultado=result;;
        		   		        	              //  CharSequence w= (CharSequence) json_data.get("re");
        		   		        	  			  //  Toast toasta=Toast.makeText(getApplicationContext(), "Inventario registrado.", 2000);
        		   						  	      //  toasta.setGravity(Gravity.CENTER,0,0);
        		   						  	      //  toasta.show();	
        		   		        	     }
        		   		        	catch(Exception e)
        		   		        	   {
        		   		        	        Log.e("log_tag", "Error parsing data "+e.toString());
        		   		        	//        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
        		   		        	    }}catch(Exception e){}
        		    		
        		    	 
        		   		finish();
        		   			 }
        		   })
        		   .setNegativeButton("No", new DialogInterface.OnClickListener() {
        		       public void onClick(DialogInterface dialog, int id) {
        		     	 
        		    	   
        		       }
        		   });
        		AlertDialog alert = builder.create();
        		alert.show();
            	
            	
            	  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.pickinglistview);
		 	listView.setAdapter(null);
		 	newPickingAdapter = new PickingAdapter(this.getApplicationContext(),databaseHelper.getAllPickLines(PO));
		  	listView.setAdapter(newPickingAdapter);
			listView.setCacheColorHint(Color.TRANSPARENT);
			listView.setSelection(INDEX);
        }
    
    @Override
    public void onBackPressed() {
        Toast.makeText(getApplicationContext(), "Para salir debe confirmar el cierre de la orden.", Toast.LENGTH_SHORT).show();
    }
    
}
