package com.example.waoperations.Shipping;

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 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.AlertDialog;
import android.app.ProgressDialog;
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.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;


import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TypefaceSpan;
import android.util.Log;
import android.view.Gravity;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class ShippingSummaryTransfer extends Activity {
	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    public String EMP,BOD,PO,USER;
    public int INDEX;
    View header;
    TextView mDisplay;
    ShippingAdapter newShippingAdapter;
    private ProgressDialog progressDialog;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ShippingDatabaseHelper databaseHelper;
    
    //private static final String TAG = "DemoActivity";
    public Double locweight,totalweight,locvolume,totalvolume,totallines,totalqty,locqty;
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shippinglist);
         header = getLayoutInflater().inflate(R.layout.header_shipping, 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");

        HeaderName.setText("SHIP ID: "+PO);

	    ListView listView = (ListView)findViewById(R.id.shippinglistview);

	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    
	actionBar.setSubtitle("Envío y Separación");
	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(newShippingAdapter);
	listView.setCacheColorHint(Color.TRANSPARENT);
	databaseHelper = new ShippingDatabaseHelper(this.getApplicationContext()); 
	databaseHelper.deleteAllData();

	 new LoadViewTask().execute();   
	 
	newShippingAdapter = new ShippingAdapter(this.getApplicationContext(),databaseHelper.getAllShippingLines());

  	listView.setAdapter(newShippingAdapter);

    }
    
    
    
    private class LoadViewTask extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  
        @Override  
        protected void onPreExecute()  
        {  
        	progressDialog = ProgressDialog.show(ShippingSummaryTransfer.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+"'"; 

            	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/getShippingListBod02.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 po=no.getString("UID");
            		    PO=po;
            	        String sku=no.getString("itemID");
            	        String qty=no.getString("qty");
            	        String factor=no.getString("factor");
            	        double receiveamount=0;
            	        double volumetotal=0;
            	        double weighttotal=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){}
            		    
            		
            		    String type=no.getString("type");
            		    if(factor.equals("null")){
                	        type="und";  
                	        }
              		    String country=no.getString("country");
              		    String barcode=no.getString("barcode");
               		    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){}
              		    
              		    
              		    if(unitconv>0){
            		    	receiveamount=receiveamount*unitconv;
            		    	  NumberFormat nf = NumberFormat.getInstance();
            		    	   qty=nf.format(receiveamount).replace(",", "").replace(".", "");
              		          weighttotal=weighttotal*unitconv;
              		    	   weight=nf.format(weighttotal).replace(",", "");
              		    		volumetotal=volumetotal*unitconv;
              		    	   volume=nf.format(volumetotal).replace(",", "");
            		    }
              		    
              		    String line=no.getString("Line");
              		    String orderid=no.getString("orderid");
              		  //String inventlocationidto=no.getString("boddestino");
        	            NumberFormat nf = NumberFormat.getInstance();
        	            nf.setMaximumFractionDigits(0);// set as you need
                        //databaseHelper.savePickLine(po,loc,sku,descripcion,qty,type,"0","0",barcode,country);
                        databaseHelper.saveShippingLine(po, sku, qty, "0", type, country, weight, volume, barcode,line,orderid,"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.getAllShippingLines();
        	if(x.getCount()==0){
         
        	}
        	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://10.10.100.13/getShippingNotProcessedList.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.UpdateShippingItem(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.");
        		}
        		
        		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","'40'"));
        		    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://10.10.100.13/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);
        		        	     //           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){}
        		

                 totalweight=0.0;
                  totalvolume=0.0; 
                  locweight=0.0;
                  locvolume=0.0;
                  totalqty=0.0;
                  locqty=0.0;
                  Cursor p =databaseHelper.getAllShippingLines();
                  p.moveToFirst();
           		while (p.moveToNext()) {
           		double indqty=Double.parseDouble(p.getString(3));
           		double indlocqty=Double.parseDouble(p.getString(4));	
           		totalqty=totalqty+indqty;
           		locqty=locqty+indlocqty;
           		totalweight=totalweight+indqty*Double.parseDouble(p.getString(7));
           		locweight=locweight+indlocqty*Double.parseDouble(p.getString(7));
           		totalvolume=totalvolume+indqty*Double.parseDouble(p.getString(8));
           		locvolume=locvolume+indlocqty*Double.parseDouble(p.getString(8));

           		}
        
        	}
     
            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();  
            
            Cursor x =databaseHelper.getAllShippingLines();
        	if(x.getCount()==0){
            //.makeText(getBaseContext(), "No hay líneas por enviar.", Toast.LENGTH_LONG).show();
            TextView Weight = (TextView) header.findViewById(R.id.weight);
            Typeface fontbold2 = Typeface.createFromAsset(ShippingSummaryTransfer.this.getAssets(), "fonts/opensans-semibold.ttf"); 
            Weight.setTypeface(fontbold2);
            Weight.setText("Líneas: 0 de 0 (0%)");
            
            TextView Desc = (TextView) header.findViewById(R.id.descripcion);
            Desc.setText("Descripción: ");
            Desc.setTypeface(fontbold2);
            
            TextView Volume = (TextView) header.findViewById(R.id.volume);
            Volume.setText("Bultos: 0 de 0 (0%)");
            Volume.setTypeface(fontbold2);
            
        	}
        	else{
        		NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(0);// set as you need
                
               double percentageamount= (locqty/totalqty)*100;
                
                TextView Weight = (TextView) header.findViewById(R.id.weight);
                Weight.setText("Líneas: "+nf.format(locweight)+" de "+nf.format(totalweight));
                Typeface fontbold2 = Typeface.createFromAsset(ShippingSummaryTransfer.this.getAssets(), "fonts/opensans-semibold.ttf"); 
                Weight.setTypeface(fontbold2);
                
                TextView Desc = (TextView) header.findViewById(R.id.descripcion);
                Desc.setText("Descripción: ");
                Desc.setTypeface(fontbold2);
                
                TextView Volume = (TextView) header.findViewById(R.id.volume);
                Volume.setText("Bultos: "+nf.format(locqty)+" de "+nf.format(totalqty)+" ("+nf.format(percentageamount)+"%)");
                Volume.setTypeface(fontbold2);
            
        	}
            //initialize the View  
		 	ListView listView = (ListView)findViewById(R.id.shippinglistview);
			listView.setAdapter(null);
			newShippingAdapter = new ShippingAdapter(ShippingSummaryTransfer.this,databaseHelper.getAllShippingLines());
			listView.setAdapter(newShippingAdapter);
			listView.setCacheColorHint(Color.TRANSPARENT);
			
			
			swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
			swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			      @Override
			      public void onRefresh() {
			    	  new LoadViewTaskRefresh().execute();   
			    		databaseHelper.deleteAllData();
			        
			  }});
		
			swipeRefreshLayout.setColorScheme(
					R.color.Gray, R.color.green, R.color.ForestGreen,R.color.Cyan);
        }
    
    }
    
    private class LoadViewTaskRefresh extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  
        @Override  
        protected void onPreExecute()  
        {  
      //  	progressDialog = ProgressDialog.show(ShippingSummaryTransfer.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+"'"; 

            	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/getShippingListBod02.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 po=no.getString("UID");
            		    PO=po;
            	        String sku=no.getString("itemID");
            	        String qty=no.getString("qty");
            	        String factor=no.getString("factor");
            	      
            	        double receiveamount=0;
            	        double volumetotal=0;
            	        double weighttotal=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){}
            		    
            		
            		    String type=no.getString("type");
            		    if(factor.equals("null")){
            	        type="und";  
            	        }
              		    String country=no.getString("country");
              		    String barcode=no.getString("barcode");
              		 
               		    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){}
              		    
              		    
              		    if(unitconv>0){
            		    	receiveamount=receiveamount*unitconv;
            		    	  NumberFormat nf = NumberFormat.getInstance();
            		    	   qty=nf.format(receiveamount).replace(",", "").replace(".", "");;
              		          weighttotal=weighttotal*unitconv;
              		    	   weight=nf.format(weighttotal).replace(",", "");
              		    		volumetotal=volumetotal*unitconv;
              		    	   volume=nf.format(volumetotal).replace(",", "");
            		    }
              		    
              		    String line=no.getString("Line");
              		   String orderid=no.getString("orderid");
              		 //String inventlocationidto= no.getString("boddestino");
        	            NumberFormat nf = NumberFormat.getInstance();
        	            nf.setMaximumFractionDigits(0);// set as you need
                        //databaseHelper.savePickLine(po,loc,sku,descripcion,qty,type,"0","0",barcode,country);
                        databaseHelper.saveShippingLine(po, sku, qty, "0", type, country, weight, volume, barcode,line,orderid,"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.getAllShippingLines();
        	if(x.getCount()==0){
         
        	}
        	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://10.10.100.13/getShippingNotProcessedList.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.UpdateShippingItem(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.");
        		}
        		
        		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","'Shipping'"));
        		    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://10.10.100.13/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);
        		        	     //           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){}
  
                 totalweight=0.0;
                  totalvolume=0.0; 
                  locweight=0.0;
                  locvolume=0.0;
                  totalqty=0.0;
                  locqty=0.0;
               Cursor p =databaseHelper.getAllShippingLines();
               p.moveToFirst();
        		while (p.moveToNext()) {
        		double indqty=Double.parseDouble(p.getString(3));
        		double indlocqty=Double.parseDouble(p.getString(4));	
                totalqty=totalqty+indqty;
                locqty=locqty+indlocqty;
        		totalweight=totalweight+indqty*Double.parseDouble(p.getString(7));
        		locweight=locweight+indlocqty*Double.parseDouble(p.getString(7));
        		totalvolume=totalvolume+indqty*Double.parseDouble(p.getString(8));
        		locvolume=locvolume+indlocqty*Double.parseDouble(p.getString(8));
        		}
        
        	}
     
            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();  
            
            Cursor x =databaseHelper.getAllShippingLines();
        	if(x.getCount()==0){
            //.makeText(getBaseContext(), "No hay líneas por enviar.", Toast.LENGTH_LONG).show();
            TextView Weight = (TextView) header.findViewById(R.id.weight);
            Weight.setText("Descripción:");
            Typeface fontbold2 = Typeface.createFromAsset(ShippingSummaryTransfer.this.getAssets(), "fonts/opensans-semibold.ttf"); 
            Weight.setTypeface(fontbold2);
            TextView Volume = (TextView) header.findViewById(R.id.volume);
            Volume.setText("Bultos: 0 de 0");
            Volume.setTypeface(fontbold2);
        	}
        	else{
        		NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(3);// set as you need
                TextView Weight = (TextView) header.findViewById(R.id.weight);
                Weight.setText("Líneas: "+nf.format(locweight)+" de "+nf.format(totalweight));
                Typeface fontbold2 = Typeface.createFromAsset(ShippingSummaryTransfer.this.getAssets(), "fonts/opensans-semibold.ttf"); 
                Weight.setTypeface(fontbold2);
                TextView Volume = (TextView) header.findViewById(R.id.volume);
                Volume.setText("Bultos: "+nf.format(locqty)+" de "+nf.format(totalqty));
                Volume.setTypeface(fontbold2);
            
        	}
            //initialize the View  
		 	ListView listView = (ListView)findViewById(R.id.shippinglistview);
		 	listView.setAdapter(null);
		 	newShippingAdapter = new ShippingAdapter(ShippingSummaryTransfer.this,databaseHelper.getAllShippingLines());
		  	listView.setAdapter(newShippingAdapter);
			listView.setCacheColorHint(Color.TRANSPARENT);
			
			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);
        }
    
    }
    
    
    
    @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() ,ShippingDetailTransfer.class);
            	intento.putExtra("PO", PO);
           	    intento.putExtra("EX","0"); 
          	    intento.putExtra("DATA",EMP); 
          	    intento.putExtra("USER",USER); 
             	  intento.putExtra("BOD",BOD); 
          	  ListView listView = (ListView)findViewById(R.id.shippinglistview);
        	    INDEX = listView.getFirstVisiblePosition();
        	    startActivity(intento);
                return true;
                
            case R.id.upload:
            	     
                String mensaje="";
                
                
             
                Cursor cursor = databaseHelper.getRemainingShippingLines(PO);
                cursor.moveToFirst();
                if (cursor.getCount()>0){
                mensaje="Faltan "+cursor.getCount()+ " líneas por revisar. Está seguro de que desea cerrar la revisión?";
                }
                else{
                mensaje="Está seguro de que desea terminar la revisión?";
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
        		builder.setMessage(mensaje)
        		   .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","'41'"));
        		   		    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://10.10.100.13/insertUserLogWA.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();
            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.shippinglistview);
		 	listView.setAdapter(null);
		 	newShippingAdapter = new ShippingAdapter(this.getApplicationContext(),databaseHelper.getAllShippingLines());
		  	listView.setAdapter(newShippingAdapter);
			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();
    }
    
}
