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


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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 com.example.waoperations.Shipping.ShippingDetail;


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.content.SharedPreferences;
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.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.ArrayAdapter;
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;

/**
 * Main UI for the demo app.
 */
public class ReceivingSummary extends Activity {
	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    public String EMP,BOD,PO,USER;
    public int INDEX;
    private ProgressDialog progressDialog;
    private SwipeRefreshLayout swipeRefreshLayout;
    TextView mDisplay;
    ReceivingAdapter newReceivingAdapter;
    
    private ReceivingDatabaseHelper databaseHelper;
    //private static final String TAG = "DemoActivity";
    
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.receivinglist);
        View header = getLayoutInflater().inflate(R.layout.header_receiving, 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("RECEIVE ID: "+PO);
	    ListView listView = (ListView)findViewById(R.id.receivinglistview);
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    
	    actionBar.setSubtitle("Receiving");
	    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(newReceivingAdapter);
	listView.setCacheColorHint(Color.TRANSPARENT);
	databaseHelper = new ReceivingDatabaseHelper(this.getApplicationContext()); 
	databaseHelper.deleteAllData();
	
	 new LoadViewTask().execute();        
	 
	 	newReceivingAdapter = new ReceivingAdapter(this.getApplicationContext(),databaseHelper.getAllReceivingLines(PO));

    	listView.setAdapter(newReceivingAdapter); 
    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;

        }
    };

    // Setting the item click listener for the listview
    listView.setOnItemClickListener(itemClickListener);
	
	
    }
    
    
    //To use the AsyncTask, it must be subclassed  
    private class LoadViewTask extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  
        @Override  
        protected void onPreExecute()  
        {  
        	progressDialog = ProgressDialog.show(ReceivingSummary.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/getReceivingList.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;
      	    		    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 line=no.getString("Line");
      	      		  
      	      		
      		            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);
      		            if(receiveamount>0){
      		            	
      	                databaseHelper.saveReceiveLine(po, sku, qty.replace(".", ""), "0", type, country, "",barcode,line,"3");
      	                }
      		            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.getAllReceivingLines(PO);
      		if(x.getCount()==0){
      	  //  Toast.makeText(getBaseContext(), "No hay líneas por recibir.", 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://10.10.100.13/getReceivingNotProcessedList.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 COUNTRYRECEIVED=no.getString("COUNTRYRECEIVED");
      		    
      		    	        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(".","").replace(",", ".");
      		        		    
      		        		}catch(Exception e){}

      		    		
      		      		    String itrans=no.getString("INVENTTRANSID");
      		      		    String itemid=no.getString("ITEMID");
      			            NumberFormat nf = NumberFormat.getInstance();
      			            nf.setMaximumFractionDigits(0);// set as you need
      			        	Cursor xyz =databaseHelper.getItemDetail(PO,itrans,itemid);
      			    		if(xyz.getCount()>0){
      			    		xyz.moveToFirst();
      		                databaseHelper.UpdateReceivingItem(COUNTED, COUNTRYRECEIVED, 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","'10'"));
      			    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{

      			        		
      			        		
      			        	     }
      			        	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.receivinglist);
            View header = getLayoutInflater().inflate(R.layout.header_receiving, 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("RECEIVE ID: "+PO);
    	    ListView listView = (ListView)findViewById(R.id.receivinglistview);
    	
    	    ActionBar actionBar = getActionBar();
    	    actionBar.hide();
    	    // more stuff here...
    	    
    	actionBar.setSubtitle("Receiving");
    	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(ReceivingSummary.this.getAssets(), "fonts/opensans-extrabold.ttf"); 
    	HeaderName.setTypeface(fontbold);
    	listView.addHeaderView(header);
    	listView.setAdapter(newReceivingAdapter);
    	listView.setCacheColorHint(Color.TRANSPARENT);

    	
   
	 	listView.setAdapter(null);
	 	newReceivingAdapter = new ReceivingAdapter(ReceivingSummary.this,databaseHelper.getAllReceivingLines(PO));
	  	listView.setAdapter(newReceivingAdapter);
		listView.setCacheColorHint(Color.TRANSPARENT);
		
		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);
        }
    
    }
   
    //To use the AsyncTask, it must be subclassed  
    private class LoadViewTaskRefresh extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  
        @Override  
        protected void onPreExecute()  
        {  
       // 	progressDialog = ProgressDialog.show(ReceivingSummary.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/getReceivingList.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;
      	    		    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 line=no.getString("Line");
      	      		  
      	      		
      		            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);
      		            if(receiveamount>0){
      	                databaseHelper.saveReceiveLine(po, sku, qty.replace(".", ""), "0", type, country, "",barcode,line,"3");
      	                }
      		            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.getAllReceivingLines(PO);
      		if(x.getCount()==0){
      	//    Toast.makeText(getBaseContext(), "No hay líneas por recibir.", 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://10.10.100.13/getReceivingNotProcessedList.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 COUNTRYRECEIVED=no.getString("COUNTRYRECEIVED");
      		    
      		    	        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(".","").replace(",", ".");
      		        		    
      		        		}catch(Exception e){}

      		    		
      		      		    String itrans=no.getString("INVENTTRANSID");
      		      		    String itemid=no.getString("ITEMID");
      			            NumberFormat nf = NumberFormat.getInstance();
      			            nf.setMaximumFractionDigits(0);// set as you need
      			        	Cursor xyz =databaseHelper.getItemDetail(PO,itrans,itemid);
      			    		if(xyz.getCount()>0){
      			    		xyz.moveToFirst();
      		                databaseHelper.UpdateReceivingItem(COUNTED, COUNTRYRECEIVED, 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","'10'"));
      			    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{

      			        		
      			        		
      			        	     }
      			        	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  
     

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

            Typeface fontbold = Typeface.createFromAsset(ReceivingSummary.this.getAssets(), "fonts/opensans-extrabold.ttf"); 
    
         	listView.setAdapter(newReceivingAdapter);
    	    listView.setCacheColorHint(Color.TRANSPARENT);

	 	listView.setAdapter(null);
	 	newReceivingAdapter = new ReceivingAdapter(ReceivingSummary.this,databaseHelper.getAllReceivingLines(PO));
	  	listView.setAdapter(newReceivingAdapter);
		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() ,ReceivingDetail.class);
        	intento.putExtra("PO", PO);
       	    intento.putExtra("EX","0"); 
      	    intento.putExtra("DATA",EMP); 
      	    intento.putExtra("USER",USER); 
        	ListView listView = (ListView)findViewById(R.id.receivinglistview);
      	    INDEX = listView.getFirstVisiblePosition();
    	    startActivity(intento);
            return true;
            
        case R.id.upload:
        	     
            String mensaje="";
            Cursor cursor = databaseHelper.getRemainingReceivingLines(PO);
            cursor.moveToFirst();
            if (cursor.getCount()>0){
            mensaje="Faltan "+cursor.getCount()+ " líneas por revisar. Esta 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","'11'"));
    		   		    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", .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.receivinglistview);
		 	listView.setAdapter(null);
		 	newReceivingAdapter = new ReceivingAdapter(this.getApplicationContext(),databaseHelper.getAllReceivingLines(PO));
		  	listView.setAdapter(newReceivingAdapter);
			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();
    }
    
 
  
    
    
}
