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


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 StatsSummary extends Activity {
	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	public String BOD,EMP,PO,USER,EQUIPO,USERCODE,MOTIVE,OP,LINES;
	int INDEX;
    TextView mDisplay;
    StatsAdapter newStatsAdapter;
    private ProgressDialog progressDialog;
    private SwipeRefreshLayout swipeRefreshLayout;
    private StatsDatabaseHelper databaseHelper;
    //private static final String TAG = "DemoActivity";
    
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.statslist);
        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");	
	//    PO=EMP;
        HeaderName.setText("STATS");
	    ListView listView = (ListView)findViewById(R.id.statslistview);
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    
	    actionBar.setSubtitle("Stats");
	    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(newStatsAdapter);
	    listView.setCacheColorHint(Color.TRANSPARENT);
	    databaseHelper = new StatsDatabaseHelper(this.getApplicationContext()); 
	    databaseHelper.deleteAllData();
	    new LoadViewTask().execute();  
	    newStatsAdapter = new StatsAdapter(this.getApplicationContext(),databaseHelper.getAllPickLines());
  	    listView.setAdapter(newStatsAdapter);
  	

  	    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() ,StatsDetail.class);
         	//intento.putExtra("PO", PO);
     	   
     	    intento.putExtra("INDEX",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(StatsSummary.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));
     	      	
     	      	
     	//apartir de aqui carga ruta
     		try
     		{
     	    	        HttpClient httpclient = new DefaultHttpClient();
     	    	        HttpPost httppost = new HttpPost("http://10.10.100.13/getStatsList.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 UID=no.getString("usercode");
     	    		  String name=no.getString("fullname");
     	    		  String lastdate=no.getString("date");
     	      		  String lastop=no.getString("motive");
     	      		  MOTIVE=lastop;
     	      		  String lastpo=no.getString("uid")+"-"+no.getString("company");
     	      		  OP=lastpo;
     	      		  String completed=no.getString("lines");
                      LINES=completed;
                      databaseHelper.saveStatsLine(UID,name,lastdate,lastop,lastpo,"0",completed);
     		   
     	    			}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();
     	if(x.getCount()==0){
    //     Toast.makeText(getBaseContext(), "No hay líneas asociadas.", Toast.LENGTH_LONG).show();	
     	}else{

     		
     		while (x.moveToNext()) {
     		
	try{
     			
     			String result = null;
     	    	InputStream is = null;
     	  
     	   
    	    	String[] IDS = x.getString(5).split("-");
	     	    	
	     			String v1 = "'"+IDS[0]+"'";
	     		    String v2 = "'"+IDS[1]+"'"; 
   //  		    String v3 = "'"+PO+"'"; 
///    		    String v4 = "'"+EQUIPO+"'"; 

     	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     	      	nameValuePairs.add(new BasicNameValuePair("emp",v2));
     	      	nameValuePairs.add(new BasicNameValuePair("id",v1));
     	      	
     	      	
     	//apartir de aqui carga ruta
     		try
     		{
     	    	        HttpClient httpclient = new DefaultHttpClient();
     	    	        String url ="http://10.10.100.13/getReceiveStats.php";
     	    	        if(MOTIVE.equals("10")){  url ="http://10.10.100.13/getReceiveStats.php";}
     	    	        else if(MOTIVE.equals("20")){url ="http://10.10.100.13/getPutAwayStats.php";}
     	    	        else if(MOTIVE.equals("30")){url ="http://10.10.100.13/getPickingStats.php";}
     	    	        else if(MOTIVE.equals("40")){url ="http://10.10.100.13/getShippingStats.php";}
     	    	        else if(MOTIVE.equals("50")){url ="http://10.10.100.13/getCCStats.php";}
     	    	        HttpPost httppost = new HttpPost(url);
     	    	        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 COUNT=no.getString("COUNT");
     	    		

                      databaseHelper.UpdateScannedAmountItem(COUNT,x.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.");
     		}
     		
     		}	
	
     	
     	
     		
     	}
      	
     
            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.statslist);
            View header = getLayoutInflater().inflate(R.layout.generalheader, null);
            TextView HeaderName = (TextView) header.findViewById(R.id.tableroheader);
    		Intent intent = getIntent();
    		//PO=intent.getStringExtra("PO");

            HeaderName.setText("STATS");
    	    ListView listView = (ListView)findViewById(R.id.statslistview);
    		

    	    ActionBar actionBar = getActionBar();
    	    actionBar.hide();
    	    // more stuff here...
    	    
    	    actionBar.setSubtitle("Stats");
    	    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(StatsSummary.this.getAssets(), "fonts/opensans-extrabold.ttf"); 
    	    HeaderName.setTypeface(fontbold);
    	    listView.addHeaderView(header);
        	listView.setAdapter(newStatsAdapter);
    	    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);
        
    		
    		
    			newStatsAdapter = new StatsAdapter(StatsSummary.this,databaseHelper.getAllPickLines());
      	listView.setAdapter(newStatsAdapter);
    	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() ,StatsDetail.class);
                intento.putExtra("INDEX",position+""); 
        	
         	    
        	    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));
     	      	
     	      	
     	//apartir de aqui carga ruta
     		try
     		{
     	    	        HttpClient httpclient = new DefaultHttpClient();
     	    	        HttpPost httppost = new HttpPost("http://10.10.100.13/getStatsList.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 UID=no.getString("usercode");
     	    		  String name=no.getString("fullname");
     	    		  String lastdate=no.getString("date");
     	      		  String lastop=no.getString("motive");
     	      		  MOTIVE=lastop;
     	      		  String lastpo=no.getString("uid")+"-"+no.getString("company");
     	      		  OP=lastpo;
     	      		  String completed=no.getString("lines");
                      LINES=completed;
                      databaseHelper.saveStatsLine(UID,name,lastdate,lastop,lastpo,"0",completed);
     		          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();
     	if(x.getCount()==0){
    //     Toast.makeText(getBaseContext(), "No hay líneas asociadas.", Toast.LENGTH_LONG).show();	
     	}else{
     		
     	
     		while (x.moveToNext()) {
     		
	try{
     			
     			String result = null;
     	    	InputStream is = null;
     	  
     	   
    	    	String[] IDS = x.getString(5).split("-");
	     	    	
	     			String v1 = "'"+IDS[0]+"'";
	     		    String v2 = "'"+IDS[1]+"'"; 
   //  		    String v3 = "'"+PO+"'"; 
///    		    String v4 = "'"+EQUIPO+"'"; 

     	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     	      	nameValuePairs.add(new BasicNameValuePair("emp",v2));
     	      	nameValuePairs.add(new BasicNameValuePair("id",v1));
     	      	
     	      	
     	//apartir de aqui carga ruta
     		try
     		{
     	    	        HttpClient httpclient = new DefaultHttpClient();
     	    	        String url ="http://10.10.100.13/getReceiveStats.php";
     	    	       MOTIVE=x.getString(4);
     	    	        if(MOTIVE.equals("10")){  url ="http://10.10.100.13/getReceiveStats.php";}
     	    	        else if(MOTIVE.equals("20")){url ="http://10.10.100.13/getPutAwayStats.php";}
     	    	        else if(MOTIVE.equals("30")){url ="http://10.10.100.13/getPickingStats.php";}
     	    	        else if(MOTIVE.equals("40")){url ="http://10.10.100.13/getShippingStats.php";}
     	    	        else if(MOTIVE.equals("50")){url ="http://10.10.100.13/getCCStats.php";}
     	    	        HttpPost httppost = new HttpPost(url);
     	    	        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 COUNT=no.getString("COUNT");
     	    		

                      databaseHelper.UpdateScannedAmountItem(COUNT,x.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.");
     		}
     		
     		}	
	
     	
     	}
      	
     
            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.statslist);
            View header = getLayoutInflater().inflate(R.layout.generalheader, null);
            TextView HeaderName = (TextView) header.findViewById(R.id.tableroheader);
    		Intent intent = getIntent();
    		//PO=intent.getStringExtra("PO");

    		
            HeaderName.setText("STATS");
    	    ListView listView = (ListView)findViewById(R.id.statslistview);
    		

    	    ActionBar actionBar = getActionBar();
    	    actionBar.hide();
    	    // more stuff here...
    	    
    	    actionBar.setSubtitle("Stats");
    	    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(StatsSummary.this.getAssets(), "fonts/opensans-extrabold.ttf"); 
    	    HeaderName.setTypeface(fontbold);
    	    listView.addHeaderView(header);
        	listView.setAdapter(newStatsAdapter);
    	    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);
        
    		
    		
    			newStatsAdapter = new StatsAdapter(StatsSummary.this,databaseHelper.getAllPickLines());
      	listView.setAdapter(newStatsAdapter);
    	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() ,StatsDetail.class);
            	//intento.putExtra("PO", PO);
              	 intento.putExtra("INDEX",position+""); 
             	

        	    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 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.statslistview);
		 	listView.setAdapter(null);
		 	newStatsAdapter = new StatsAdapter(this.getApplicationContext(),databaseHelper.getAllPickLines());
		  	listView.setAdapter(newStatsAdapter);
			listView.setCacheColorHint(Color.TRANSPARENT);
			listView.setSelection(INDEX);
        }
    

    
}
