package com.example.waoperations.Transference;

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 java.util.HashMap;
import java.util.List;

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

import com.example.waoperations.R;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
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.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class TransferenceZurquiSummary extends Activity{

	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	
    public String PO,USER,EMP,EMP2,BOD,BARCODE,ID,INVTID, SHIPDATE,PID,CONFIG,PED;
    public String Disponible = " ";
    public String transf = "";
    public String purch2 = "";
     public int INDEX;
     public Double fisicatotal;
    TextView mDisplay;
    View header;
    ArrayList<String> IDPurch= new ArrayList<String>();
    ArrayList<String> IDTransf = new ArrayList<String>();
    ArrayList<String> BodDest = new ArrayList<String>();
	ArrayList<String> InventTransidPO = new ArrayList<String>();
	ArrayList<String> InventTransid = new ArrayList<String>();
    TransferenceAdapterZ newTransferenceAdapterZ;
    private ProgressDialog progressDialog;
    private SwipeRefreshLayout swipeRefreshLayout;
    //private TransferenceDataBaseHelper2 databaseHelper;
	private TransferenceDataBaseHelperPO databaseHelperPO;
	private CrossDockingDataBaseHelper databaseHelperCrsDck;
	private TransferenceDataBaseHelperZ databaseHelperZ;
    //private static final String TAG = "DemoActivity";

	String FechaCreacionTransfer="";
	String Articulo="";
	String PedidoCompra="";
	Double acumulador=0.0;

    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        Typeface fontbold = Typeface.createFromAsset(this.getApplicationContext().getAssets(), "fonts/opensans-extrabold.ttf");
        
        setContentView(R.layout.transferlist_item);
        TextView HeaderName = (TextView) findViewById(R.id.tableroheader1);
    	
	    final ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    actionBar.setSubtitle("Transfer Zurquí");
	    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(); 
	    //listView.addHeaderView(header,null, false);

        HeaderName.setTypeface(fontbold);
	    //listView.addHeaderView(header);
	    listView.setAdapter(newTransferenceAdapterZ);
	    listView.setCacheColorHint(Color.TRANSPARENT);
	    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	    
	    databaseHelperZ = new TransferenceDataBaseHelperZ(this.getApplicationContext()); 
	    databaseHelperZ.deleteAllData();
	  		
	    //databaseHelper = new TransferenceDataBaseHelper2(this.getApplicationContext()); 
		//databaseHelper.deleteAllData();

		databaseHelperPO = new TransferenceDataBaseHelperPO(this.getApplicationContext());
		databaseHelperPO.deleteAllData();

		//databaseHelperCrsDck = new CrossDockingDataBaseHelper(this.getApplicationContext());
		//databaseHelperCrsDck.deleteAllData();

		Intent intent = getIntent();
		this.PO=intent.getStringExtra("PO");
		this.EMP2=intent.getStringExtra("EMP2");
		this.BOD=intent.getStringExtra("BOD");
		this.USER=intent.getStringExtra("USER");
		this.BARCODE=intent.getStringExtra("BARCODE");
		HeaderName.setText("ARTÍCULO: " +PO);
    	HeaderName.setTextSize(25);
    	
 	    new LoadViewTask().execute();   
	
 	   newTransferenceAdapterZ = new TransferenceAdapterZ(this.getApplicationContext(),databaseHelperZ.getAllTransferenciasLines());
 	  listView.setAdapter(newTransferenceAdapterZ);
	  	
	    OnItemClickListener itemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
                // Mensaje Toast del elemento seleccionado.
            	try{
            	if(position==0){ 
            		//transf=IDTransf.get(position);
            		BOD=BodDest.get(position);
					INVTID=InventTransid.get(position);
					PED=IDPurch.get(position);
									

            	}else{
            		//transf=IDTransf.get(position);
            		BOD=BodDest.get(position);
					INVTID=InventTransid.get(position);
					PED=IDPurch.get(position);
				
            	}

            	Intent intento = new Intent(getApplicationContext(), TransferenceZurquiDetail.class);  
		        	intento.putExtra("PO", PedidoCompra);
		       	    intento.putExtra("EX","0"); 
		      	  	//intento.putExtra("DATA",EMP); 
		       	   intento.putExtra("USER",USER); 
		       	   intento.putExtra("EMP2", EMP2);
		       	   intento.putExtra("BODDEST",BOD);
					intento.putExtra("INVTID",INVTID);
					intento.putExtra("CONFIG",CONFIG);
					intento.putExtra("ITEM",PO);
					intento.putExtra("PED",PED);
		       	    
		      	  ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
		    	    INDEX = listView.getFirstVisiblePosition();
		    	    listView.setAdapter(null);
		    	   
		    	     startActivity(intento);
		    	     
		    	  //  linearLayoutParent.setBackgroundColor(getResources().getColor(R.color.white));
            	}catch(NullPointerException exc){Toast.makeText(getApplicationContext(), "Error al seleccionar Item", Toast.LENGTH_SHORT).show();}
            }
             
        };
        // Setting the item click listener for the listview
	    listView.setOnItemClickListener(itemClickListener);
	    }
   
    
    private class LoadViewTask extends AsyncTask<Void, Integer, Void>  
    {  //Before running code in separate thread  
   
        @Override  
        protected void onPreExecute()  
        {  
        	progressDialog = ProgressDialog.show(TransferenceZurquiSummary.this,"Cargando...",  
        		    "Cargando informacion, favor espere...", false, false);
        }  
             //The code to be executed in a background thread.  <<
        @Override
        protected Void doInBackground(Void... params)
        {
        	StrictMode.setThreadPolicy(policy);

        	try{
        		String result1 = null;
            	InputStream is1 = null;
            	String v1 = "'"+PO+"'";
            	String v2 = "'"+EMP2+"'";
            	String v3 = "'"+BOD+"'";
            	SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd");
            	SHIPDATE = sdfs.format(new Date()); 
            	String v4= "'"+SHIPDATE+"'";

        		

            	ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
            	nameValuePairs1.add(new BasicNameValuePair("ITEMID",v1));
            	nameValuePairs1.add(new BasicNameValuePair("DATAAREAIDTO",v2));
            	nameValuePairs1.add(new BasicNameValuePair("INVENTLOCATIONIDTO",v3));
            	nameValuePairs1.add(new BasicNameValuePair("TRANSDATE",v4));

        	try
        	{
            	        HttpClient httpclient = new DefaultHttpClient();
            	        HttpPost httppost = new HttpPost("http://10.10.100.13/getTransferenciasZListByItemNew.php");
            	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
            	        HttpResponse response = httpclient.execute(httppost);
            	        HttpEntity entity = response.getEntity();
            	        is1 = entity.getContent();
            	        Log.e("log_tag", "connection success ");
        	}
        catch(Exception e)
        	{
            	        Log.e("log_tag", "Error in http connection "+e.toString());
            }

        	try{
            	        BufferedReader reader = new BufferedReader(new InputStreamReader(is1,"ISO-8859-1"),8);
            	        StringBuilder sb = new StringBuilder();
            	        String line = null;
            	        while ((line = reader.readLine()) != null)
            	        {
            	                sb.append(line + "\n");
            	        }
            	        is1.close();
						result1=sb.toString();
        	}
        	catch(Exception e)
        	{
            	       Log.e("log_tag", "Error converting result "+e.toString());
        	}

        int counter=0;

            	try{
                    databaseHelperZ.deleteAllData();

            	 	JSONArray jArray = new JSONArray(result1);
            		for(int i=0;i<jArray.length();i++)
                    {
            			try{
				            		   	JSONObject no = jArray.getJSONObject(i);
				            		   	String inventtransid =no.getString("INVENTTRANSID");
				            		   	String purchid =no.getString("PURCHID");
				            		   	String shippingid =no.getString("SHIPMENTID");
				            		   	String itemid=no.getString("ITEMID");
				            		   	String  qtytransfer=no.getString("QTY");
				            		   	//String qtycounted=no.getString("QTYCOUNTED");
				            		    String dataareaidto=no.getString("DATAAREAIDTO");
				            		   	String inventlocationidto=no.getString("INVENTLOCATIONIDTO");
				            		    String processed=no.getString("PROCESSED");
				            		    String qtyavailable=no.getString("QTY");
										String barcode= BARCODE;
										//String transdate=no.getString("");

				            		    try{
				                		    Double Qt = Double.parseDouble(qtytransfer);
				                		    NumberFormat nf = NumberFormat.getInstance();
				        	 	            nf.setMaximumFractionDigits(0);// set as you need
											qtytransfer=nf.format(Qt).replace(",", "");
				            		    	}catch(Exception e){}
										try{
											Double Qt = Double.parseDouble(qtyavailable);
											NumberFormat nf = NumberFormat.getInstance();
											nf.setMaximumFractionDigits(0);// set as you need
											qtyavailable=nf.format(Qt).replace(",", "");
										}catch(Exception e){}
										
										//SHIPDATE=sdfs.format(transdate); 
										
										INVTID=inventtransid;
										PID=purchid;
										
										if(barcode.equals(""))
										{
											barcode="-";
										}

				            		    Disponible=qtytransfer;
				            		    //IDTransf.add(transferid);
				            		    IDPurch.add(purchid);
				            		     PedidoCompra=purchid;
				            		    BodDest.add(inventlocationidto);
				            		    InventTransid.add(inventtransid);
										Articulo=itemid;

										databaseHelperZ.saveTransferenceLineZ(inventtransid,purchid,shippingid,itemid,qtytransfer,"0",dataareaidto,inventlocationidto.toUpperCase(),processed,"0",qtyavailable, barcode,"0","0","-");

				        	            counter++;

            			}catch(Exception e)
        	          	{
            				 Log.e("log_tag", "Error cargando datos "+e.toString());
        	          	}
        	            }
            	}
            	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.");
        		}
        	
			/*Consulta a pedido de Compra según pedido*/

				Cursor y =databaseHelperZ.getAllTransferenciasLines();
				//y.moveToFirst();
				if(y.getCount()==0){

				}
				else {
					
					StrictMode.setThreadPolicy(policy);

					try {
						String result2 = null;
						InputStream is2 = null;
						String v1 = "'" + Articulo + "'";
						String v2 = "'" + PedidoCompra + "'";
						String v3 = "'" + EMP2 + "'";
						String v4 = "'" + BOD + "'";

						ArrayList<NameValuePair> nameValuePairspo = new ArrayList<NameValuePair>();
						nameValuePairspo.add(new BasicNameValuePair("ITEMID", v1));
						nameValuePairspo.add(new BasicNameValuePair("PURCHID", v2));
						nameValuePairspo.add(new BasicNameValuePair("EMP2", v3));
						nameValuePairspo.add(new BasicNameValuePair("INVENTLOCATIONID", v4));

						try {
							HttpClient httpclient = new DefaultHttpClient();
							HttpPost httppost = new HttpPost("http://10.10.100.13/getTransferPurchLinesListZ.php");
							httppost.setEntity(new UrlEncodedFormEntity(nameValuePairspo));
							HttpResponse response = httpclient.execute(httppost);
							HttpEntity entity = response.getEntity();
							is2 = entity.getContent();
							Log.e("log_tag", "connection success ");
						} catch (Exception e) {
							Log.e("log_tag", "Error in http connection " + e.toString());
						}

						try {
							BufferedReader reader = new BufferedReader(new InputStreamReader(is2, "ISO-8859-1"), 8);
							StringBuilder sb2 = new StringBuilder();
							String line2 = null;
							while ((line2 = reader.readLine()) != null) {
								sb2.append(line2 + "\n");
							}
							is2.close();
							result2 = sb2.toString();
						} catch (Exception e) {
							Log.e("log_tag", "Error converting result " + e.toString());
						}

						int counter = 0;

						try {
							databaseHelperPO.deleteAllData();

							JSONArray jArray = new JSONArray(result2);
							for (int i = 0; i < jArray.length(); i++) {
								try {
									JSONObject no = jArray.getJSONObject(i);
									String purchid = no.getString("PURCHID");
									String itemid = no.getString("ITEMID");
									String purchqty = no.getString("PURCHQTY");
									String qtyordered = no.getString("QTYORDERED");
									String purchunit = no.getString("PURCHUNIT");
									String purchreceivednow = no.getString("PURCHRECEIVEDNOW");
									String purchstatus = no.getString("PURCHSTATUS");
									String orderaccount = no.getString("ORDERACCOUNT");
									String createddate = no.getString("CREATEDDATE");
									String inventlocationid = no.getString("INVENTLOCATIONID");
									String linenum = no.getString("LINENUM");

									try {
										Double Qt = Double.parseDouble(purchqty);
										NumberFormat nf = NumberFormat.getInstance();
										nf.setMaximumFractionDigits(0);// set as you need
										purchqty = nf.format(Qt).replace(",", "");
									} catch (Exception e) {
									}

									try {
										Double Qt2 = Double.parseDouble(qtyordered);
										NumberFormat nf2 = NumberFormat.getInstance();
										nf2.setMaximumFractionDigits(0);// set as you need
										qtyordered = nf2.format(Qt2).replace(",", "");
									} catch (Exception e) {
									}


									try {
										Double Qt3 = Double.parseDouble(purchreceivednow);
										NumberFormat nf3 = NumberFormat.getInstance();
										nf3.setMaximumFractionDigits(0);// set as you need
										purchreceivednow = nf3.format(Qt3).replace(",", "");
									} catch (Exception e) {
									}

									PedidoCompra = purchid;
									CONFIG=purchunit;
									
									if(CONFIG.equals(null))
									{
										CONFIG="-";
									}

									//InventTransidPO.add(inventtransid);
									String itemid2=PO;
									
									y.moveToFirst();
									
									for(int z=0;z<y.getCount();z++)
									{
										String id1 = y.getString(0);
										String conf=purchunit;

										databaseHelperZ.UpdateItem(purchunit, id1);
										y.moveToNext();
									}

									/*Cursor xyz =databaseHelperZ.getTransferItemDetail(purchid,inventtransid2,itemid2);
									if(xyz.getCount()>0)
									{
										xyz.moveToFirst();
										String id1 = xyz.getString(0);
										databaseHelperZ.UpdateItem(purchunit, id1);
									}*/

									databaseHelperPO.saveTransferencePOLine(purchid, itemid, purchqty, qtyordered, purchunit, purchreceivednow, purchstatus, orderaccount, createddate, inventlocationid, linenum,"0");

									counter++;

								} catch (Exception e) {
									Log.e("log_tag", "Error cargando datos " + e.toString());
								}
							}
						} catch (JSONException e) {
							Log.e("log_tag", "Error parsing data " + e.toString() + Integer.toString(counter));
						} catch (IllegalArgumentException e) {
							
							e.printStackTrace();
						}
					} catch (Exception e)
					{
						Log.e("log_tag", "Active el VPN para aplicar esta opción.");
					}
				}
				
			/*Fin de consulta */


	
			Cursor x =databaseHelperZ.getAllTransferenciasLines();

			if(x.getCount()==0){	}
			else{
				try{

					String result4 = null;
					InputStream is4 = null;

					String v1 = "'"+PO+"'";
					String v2 = "'"+EMP2+"'";

					SimpleDateFormat sdfa2 = new SimpleDateFormat("yyyy-MM-dd");

					ArrayList<NameValuePair> nameValuePairs4 = new ArrayList<NameValuePair>();
					nameValuePairs4.add(new BasicNameValuePair("ITEMID",v1));
					nameValuePairs4.add(new BasicNameValuePair("DATAAREAIDTO",v2));

				try
					{
						HttpClient httpclient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost("http://10.10.100.13/getTransferenciasZNotProcessedListByItemZ.php");
						httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs4));
						HttpResponse response = httpclient.execute(httppost);
						HttpEntity entity = response.getEntity();
						is4 = 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();
					}

					try{

						BufferedReader reader = new BufferedReader(new InputStreamReader(is4,"ISO-8859-1"),8);
						StringBuilder sb = new StringBuilder();
						String line = null;
						while ((line = reader.readLine()) != null)
						{
							sb.append(line + "\n");
						}
						is4.close();
						result4=sb.toString();
					}
					catch(Exception e)
					{
						Log.e("log_tag", "Error converting result "+e.toString());
					}
					int counter=0;

					try{
						//databaseHelper.deleteAllData();

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

								String CONTADA=no.getString("QTYCOUNTED");

								purch2 = no.getString("PURCHID");

								try{
									Double Qt = Double.parseDouble(CONTADA);
									NumberFormat nf = NumberFormat.getInstance();
									nf.setMaximumFractionDigits(0);// set as you need
									CONTADA=nf.format(Qt).replace(",", "");

								}catch(Exception e){}

								String DISPONIBLE=no.getString("QTYAVAILABLE");
								// Disponible=AVAILABLE;

								try{
									Double Qt = Double.parseDouble(DISPONIBLE);
									NumberFormat nf3 = NumberFormat.getInstance();
									nf3.setMaximumFractionDigits(0);// set as you need
									DISPONIBLE=nf3.format(Qt).replace(",", "");

								}catch(Exception e){}

								String SOBRANTE=no.getString("QTYREMAIN");

								try{
									Double Qt = Double.parseDouble(SOBRANTE);
									NumberFormat nf4 = NumberFormat.getInstance();
									nf4.setMaximumFractionDigits(0);// set as you need
									SOBRANTE=nf4.format(Qt).replace(",", "");

								}catch(Exception e){}


								String inventtransid=no.getString("INVENTTRANSID");
								String itemid=no.getString("ITEMID");
								NumberFormat nf = NumberFormat.getInstance();
								nf.setMaximumFractionDigits(0);// set as you need
								Cursor xyz =databaseHelperZ.getTransferItemDetail(purch2,inventtransid,itemid);
								if(xyz.getCount()>0)
								{
									xyz.moveToFirst();
									String id1 = xyz.getString(0);
									databaseHelperZ.UpdateTransferItem(CONTADA, DISPONIBLE, SOBRANTE, id1);
								}

								counter++;
							}catch(Exception e)
							{
							}
						}

					}
					catch(JSONException e)
					{
						Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}catch(Exception e)
				{
					Log.e("log_tag", "Active el VPN para aplicar esta opción.");
				}


	
       			}
			
			
		


			return null;
        }
        																																																																																																																																																																																																																																																																																																														
      //Update the progress  
        @Override  
        protected void onProgressUpdate(Integer... values)  
        {  
            //set the current progress of the progress dialog  
            progressDialog.setProgress(values[0]);  
        }  
        
         //after executing the code in the thread  
        @Override  
        protected void onPostExecute(Void result)      
        {  
            progressDialog.dismiss();
            
            Cursor x =databaseHelperZ.getAllTransferenciasLines();
        	if(x.getCount()==0){
           		Toast.makeText(getBaseContext(), "No hay transferencias por contar para este artículo o ya han sido ejecutadas.", Toast.LENGTH_LONG).show();
        		
				TextView DesdeA = (TextView) findViewById(R.id.qtydisponible);
                Typeface fontbold2 = Typeface.createFromAsset(TransferenceZurquiSummary.this.getAssets(), "fonts/opensans-semibold.ttf"); 
                DesdeA.setTypeface(fontbold2);
                DesdeA.setText("Lista de Chequeo PDA Zurquí");
                DesdeA.setTextColor(Color.BLACK);
                DesdeA.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
      
        	}  
        	else
        	{
        		NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(0);// set as you need
                
        		TextView DesdeA = (TextView) findViewById(R.id.qtydisponible);
                Typeface fontbold2 = Typeface.createFromAsset(TransferenceZurquiSummary.this.getAssets(), "fonts/opensans-semibold.ttf"); 
                DesdeA.setTypeface(fontbold2);
                DesdeA.setText("Lista de Chequeo PDA Zurquí");
                DesdeA.setTextColor(Color.BLACK);
                DesdeA.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
               	}

        	//initialize the View  
        		ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
        		listView.setAdapter(null);
        		newTransferenceAdapterZ = new TransferenceAdapterZ(TransferenceZurquiSummary.this,databaseHelperZ.getAllTransferenciasLines());
    		  	listView.setAdapter(newTransferenceAdapterZ );
    			listView.setCacheColorHint(Color.TRANSPARENT);


            }
    
    }
  
    
    private class LoadViewTaskRefresh extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  

		@Override
		protected Void doInBackground(Void... params)
		{
        	StrictMode.setThreadPolicy(policy);

        	try{
        		String result1 = null;
            	InputStream is1 = null;
            	String v1 = "'"+PO+"'";
            	String v2 = "'"+EMP2+"'";
            	String v3 = "'"+BOD+"'";
            	SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd");
            	SHIPDATE = sdfs.format(new Date()); 
            	String v4= "'"+SHIPDATE+"'";

        		

            	ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
            	nameValuePairs1.add(new BasicNameValuePair("ITEMID",v1));
            	nameValuePairs1.add(new BasicNameValuePair("DATAAREAIDTO",v2));
            	nameValuePairs1.add(new BasicNameValuePair("INVENTLOCATIONIDTO",v3));
            	nameValuePairs1.add(new BasicNameValuePair("TRANSDATE",v4));

        	try
        	{
            	        HttpClient httpclient = new DefaultHttpClient();
            	        HttpPost httppost = new HttpPost("http://10.10.100.13/getTransferenciasZListByItemNew.php");
            	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
            	        HttpResponse response = httpclient.execute(httppost);
            	        HttpEntity entity = response.getEntity();
            	        is1 = entity.getContent();
            	        Log.e("log_tag", "connection success ");
        	}
        catch(Exception e)
        	{
            	        Log.e("log_tag", "Error in http connection "+e.toString());
            }

        	try{
            	        BufferedReader reader = new BufferedReader(new InputStreamReader(is1,"ISO-8859-1"),8);
            	        StringBuilder sb = new StringBuilder();
            	        String line = null;
            	        while ((line = reader.readLine()) != null)
            	        {
            	                sb.append(line + "\n");
            	        }
            	        is1.close();
						result1=sb.toString();
        	}
        	catch(Exception e)
        	{
            	       Log.e("log_tag", "Error converting result "+e.toString());
        	}

        int counter=0;

            	try{
                    databaseHelperZ.deleteAllData();

            	 	JSONArray jArray = new JSONArray(result1);
            		for(int i=0;i<jArray.length();i++)
                    {
            			try{
				            		   	JSONObject no = jArray.getJSONObject(i);
				            		   	String inventtransid =no.getString("INVENTTRANSID");
				            		   	String purchid =no.getString("PURCHID");
				            		   	String shippingid =no.getString("SHIPMENTID");
				            		   	String itemid=no.getString("ITEMID");
				            		   	String  qtytransfer=no.getString("QTY");
				            		   	//String qtycounted=no.getString("QTYCOUNTED");
				            		    String dataareaidto=no.getString("DATAAREAIDTO");
				            		   	String inventlocationidto=no.getString("INVENTLOCATIONIDTO");
				            		    String processed=no.getString("PROCESSED");
				            		    String qtyavailable=no.getString("QTY");
										String barcode= BARCODE;
										//String transdate=no.getString("");

				            		    try{
				                		    Double Qt = Double.parseDouble(qtytransfer);
				                		    NumberFormat nf = NumberFormat.getInstance();
				        	 	            nf.setMaximumFractionDigits(0);// set as you need
											qtytransfer=nf.format(Qt).replace(",", "");
				            		    	}catch(Exception e){}
										try{
											Double Qt = Double.parseDouble(qtyavailable);
											NumberFormat nf = NumberFormat.getInstance();
											nf.setMaximumFractionDigits(0);// set as you need
											qtyavailable=nf.format(Qt).replace(",", "");
										}catch(Exception e){}
										
										//SHIPDATE=sdfs.format(transdate); 
										
										INVTID=inventtransid;
										PID=purchid;
										
										if(barcode.equals(""))
										{
											barcode="-";
										}

				            		    Disponible=qtytransfer;
				            		    //IDTransf.add(transferid);
				            		    IDPurch.add(purchid);
				            		    PedidoCompra=purchid;
				            		    BodDest.add(inventlocationidto);
				            		    InventTransid.add(inventtransid);
										Articulo=itemid;

										databaseHelperZ.saveTransferenceLineZ(inventtransid,purchid,shippingid,itemid,qtytransfer,"0",dataareaidto,inventlocationidto.toUpperCase(),processed,"0",qtyavailable, barcode,"0","0","-");
										
				        	            counter++;

            			}catch(Exception e)
        	          	{
            				 Log.e("log_tag", "Error cargando datos "+e.toString());
        	          	}
        	            }
            	}
            	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.");
        		}
        	
       

			
			/*Consulta a pedido de Compra según pedido*/

				Cursor y =databaseHelperZ.getAllTransferenciasLines();
				y.moveToFirst();
				if(y.getCount()==0){

				}
				else {
					
					StrictMode.setThreadPolicy(policy);

					try {
						String result2 = null;
						InputStream is2 = null;
						String v1 = "'" + Articulo + "'";
						String v2 = "'" + PedidoCompra + "'";
						String v3 = "'" + EMP2 + "'";
						String v4 = "'" + BOD + "'";

						ArrayList<NameValuePair> nameValuePairspo = new ArrayList<NameValuePair>();
						nameValuePairspo.add(new BasicNameValuePair("ITEMID", v1));
						nameValuePairspo.add(new BasicNameValuePair("PURCHID", v2));
						nameValuePairspo.add(new BasicNameValuePair("EMP2", v3));
						nameValuePairspo.add(new BasicNameValuePair("INVENTLOCATIONID", v4));

						try {
							HttpClient httpclient = new DefaultHttpClient();
							HttpPost httppost = new HttpPost("http://10.10.100.13/getTransferPurchLinesListZ.php");
							httppost.setEntity(new UrlEncodedFormEntity(nameValuePairspo));
							HttpResponse response = httpclient.execute(httppost);
							HttpEntity entity = response.getEntity();
							is2 = entity.getContent();
							Log.e("log_tag", "connection success ");
						} catch (Exception e) {
							Log.e("log_tag", "Error in http connection " + e.toString());
						}

						try {
							BufferedReader reader = new BufferedReader(new InputStreamReader(is2, "ISO-8859-1"), 8);
							StringBuilder sb = new StringBuilder();
							String line = null;
							while ((line = reader.readLine()) != null) {
								sb.append(line + "\n");
							}
							is2.close();
							result2 = sb.toString();
						} catch (Exception e) {
							Log.e("log_tag", "Error converting result " + e.toString());
						}

						int counter = 0;

						try {
							databaseHelperPO.deleteAllData();

							JSONArray jArray = new JSONArray(result2);
							for (int i = 0; i < jArray.length(); i++) {
								try {
									JSONObject no = jArray.getJSONObject(i);
									String purchid = no.getString("PURCHID");
									String itemid = no.getString("ITEMID");
									String purchqty = no.getString("PURCHQTY");
									String qtyordered = no.getString("QTYORDERED");
									String purchunit = no.getString("PURCHUNIT");
									String purchreceivednow = no.getString("PURCHRECEIVEDNOW");
									String purchstatus = no.getString("PURCHSTATUS");
									String orderaccount = no.getString("ORDERACCOUNT");
									String createddate = no.getString("CREATEDDATE");
									String inventlocationid = no.getString("INVENTLOCATIONID");
									String linenum = no.getString("LINENUM");

									try {
										Double Qt = Double.parseDouble(purchqty);
										NumberFormat nf = NumberFormat.getInstance();
										nf.setMaximumFractionDigits(0);// set as you need
										purchqty = nf.format(Qt).replace(",", "");
									} catch (Exception e) {
									}

									try {
										Double Qt2 = Double.parseDouble(qtyordered);
										NumberFormat nf2 = NumberFormat.getInstance();
										nf2.setMaximumFractionDigits(0);// set as you need
										qtyordered = nf2.format(Qt2).replace(",", "");
									} catch (Exception e) {
									}


									try {
										Double Qt3 = Double.parseDouble(purchreceivednow);
										NumberFormat nf3 = NumberFormat.getInstance();
										nf3.setMaximumFractionDigits(0);// set as you need
										purchreceivednow = nf3.format(Qt3).replace(",", "");
									} catch (Exception e) {
									}

									PedidoCompra = purchid;
									CONFIG=purchunit;

									//InventTransidPO.add(inventtransid);

									String inventtransid2=y.getString(11);
									String itemid2=PO;

									Cursor xyz =databaseHelperZ.getTransferItemDetail(purchid,inventtransid2,itemid2);
									if(xyz.getCount()>0)
									{
										xyz.moveToFirst();
										String id1 = xyz.getString(0);
										//databaseHelper.UpdateItem(qtyordered, id1);
									}

									databaseHelperPO.saveTransferencePOLine(purchid, itemid, purchqty, qtyordered, purchunit, purchreceivednow, purchstatus, orderaccount, createddate, inventlocationid, linenum,"0");

									counter++;

								} catch (Exception e) {
									Log.e("log_tag", "Error cargando datos " + e.toString());
								}
							}
						} catch (JSONException e) {
							Log.e("log_tag", "Error parsing data " + e.toString() + Integer.toString(counter));
						} catch (IllegalArgumentException e) {
							
							e.printStackTrace();
						}
					} catch (Exception e)
					{
						Log.e("log_tag", "Active el VPN para aplicar esta opción.");
					}
				}
				
			/*Fin de consulta */


	
			Cursor x =databaseHelperZ.getAllTransferenciasLines();

			if(x.getCount()==0){	}
			else{
				try{

					String result4 = null;
					InputStream is4 = null;

					String v1 = "'"+PO+"'";
					String v2 = "'"+EMP2+"'";

					SimpleDateFormat sdfa2 = new SimpleDateFormat("yyyy-MM-dd");

					ArrayList<NameValuePair> nameValuePairs4 = new ArrayList<NameValuePair>();
					nameValuePairs4.add(new BasicNameValuePair("ITEMID",v1));
					nameValuePairs4.add(new BasicNameValuePair("DATAAREAIDTO",v2));

				try
					{
						HttpClient httpclient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost("http://10.10.100.13/getTransferenciasZNotProcessedListByItemZ.php");
						httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs4));
						HttpResponse response = httpclient.execute(httppost);
						HttpEntity entity = response.getEntity();
						is4 = 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();
					}

					try{

						BufferedReader reader = new BufferedReader(new InputStreamReader(is4,"ISO-8859-1"),8);
						StringBuilder sb = new StringBuilder();
						String line = null;
						while ((line = reader.readLine()) != null)
						{
							sb.append(line + "\n");
						}
						is4.close();
						result4=sb.toString();
					}
					catch(Exception e)
					{
						Log.e("log_tag", "Error converting result "+e.toString());
					}
					int counter=0;

					try{
						//databaseHelper.deleteAllData();

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

								String CONTADA=no.getString("QTYCOUNTED");

								purch2 = no.getString("PURCHID");

								try{
									Double Qt = Double.parseDouble(CONTADA);
									NumberFormat nf = NumberFormat.getInstance();
									nf.setMaximumFractionDigits(0);// set as you need
									CONTADA=nf.format(Qt).replace(",", "");

								}catch(Exception e){}

								String DISPONIBLE=no.getString("QTYAVAILABLE");
								// Disponible=AVAILABLE;

								try{
									Double Qt = Double.parseDouble(DISPONIBLE);
									NumberFormat nf3 = NumberFormat.getInstance();
									nf3.setMaximumFractionDigits(0);// set as you need
									DISPONIBLE=nf3.format(Qt).replace(",", "");

								}catch(Exception e){}

								String SOBRANTE=no.getString("QTYREMAIN");

								try{
									Double Qt = Double.parseDouble(SOBRANTE);
									NumberFormat nf4 = NumberFormat.getInstance();
									nf4.setMaximumFractionDigits(0);// set as you need
									SOBRANTE=nf4.format(Qt).replace(",", "");

								}catch(Exception e){}


								String inventtransid=no.getString("INVENTTRANSID");
								String itemid=no.getString("ITEMID");
								NumberFormat nf = NumberFormat.getInstance();
								nf.setMaximumFractionDigits(0);// set as you need
								Cursor xyz =databaseHelperZ.getTransferItemDetail(purch2,inventtransid,itemid);
								if(xyz.getCount()>0)
								{
									xyz.moveToFirst();
									String id1 = xyz.getString(0);
									databaseHelperZ.UpdateTransferItem(CONTADA, DISPONIBLE, SOBRANTE, id1);
								}

								counter++;
							}catch(Exception e)
							{
							}
						}

					}
					catch(JSONException e)
					{
						Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}catch(Exception e)
				{
					Log.e("log_tag", "Active el VPN para aplicar esta opción.");
				}


	
       			}
			
			
		


			return null;
        }

		//Update the progress
		@Override
		protected void onProgressUpdate(Integer... values)
		{
			//set the current progress of the progress dialog
			progressDialog.setProgress(values[0]);
		}

		//after executing the code in the thread
		@Override
		protected void onPostExecute(Void result)
		{
			progressDialog.dismiss();

			Cursor x =databaseHelperZ.getAllTransferenciasLines();
			if(x.getCount()==0){
				Toast.makeText(getBaseContext(), "No hay transferencias por contar para este artículo o ya han sido ejecutadas.", Toast.LENGTH_LONG).show();

				TextView DesdeA = (TextView) findViewById(R.id.qtydisponible);
				Typeface fontbold2 = Typeface.createFromAsset(TransferenceZurquiSummary.this.getAssets(), "fonts/opensans-semibold.ttf");
				DesdeA.setTypeface(fontbold2);
				DesdeA.setText("Lista de Chequeo PDA Zurquí");
				DesdeA.setTextColor(Color.BLACK);
				DesdeA.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);

			}
			else
			{
				NumberFormat nf = NumberFormat.getInstance();
				nf.setMaximumFractionDigits(0);// set as you need

				TextView DesdeA = (TextView) findViewById(R.id.qtydisponible);
				Typeface fontbold2 = Typeface.createFromAsset(TransferenceZurquiSummary.this.getAssets(), "fonts/opensans-semibold.ttf");
				DesdeA.setTypeface(fontbold2);
				DesdeA.setText("Lista de Chequeo PDA Zurquí");
				DesdeA.setTextColor(Color.BLACK);
				DesdeA.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
			}

			//initialize the View
			ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
			listView.setAdapter(null);
			newTransferenceAdapterZ = new TransferenceAdapterZ(TransferenceZurquiSummary.this,databaseHelperZ.getAllTransferenciasLines());
			listView.setAdapter(newTransferenceAdapterZ );
			listView.setCacheColorHint(Color.TRANSPARENT);


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


    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle presses on the action bar items
    	  	int id = item.getItemId();
	    	if (id == R.id.refresh)
	    	{
	    		ArrayList<HashMap<String,Object>> items =new ArrayList<HashMap<String,Object>>();
	    		PackageManager pm;
	    		final PackageManager pm2 = getPackageManager();
	    		List<PackageInfo> packs = pm2.getInstalledPackages(0);  
	    		for (PackageInfo pi : packs) {
	    		if( pi.packageName.toString().toLowerCase().contains("calcul")){
	    		    HashMap<String, Object> map = new HashMap<String, Object>();
	    		    map.put("appName", pi.applicationInfo.loadLabel(pm2));
	    		    map.put("packageName", pi.packageName);
	    		    items.add(map);
	    		 }
	    		}
	    		
	    		if(items.size()>=1){
	    			String packageName = (String) items.get(0).get("packageName");
	    			Intent i = pm2.getLaunchIntentForPackage(packageName);
	    			if (i != null)
	    			  startActivity(i);
	    			} 
	    			else{
	    			      // Application not found
	    			   }

	    	} else if (id == R.id.refresh) {

	    		progressDialog.dismiss(); 
	    		
	    		databaseHelperZ.deleteAllData();
	    		new LoadViewTaskRefresh().execute();  
	    		
	    	}
                    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
		/*progressDialog.dismiss(); 
        databaseHelper.deleteAllData();
		new LoadViewTaskRefresh().execute();  */
        
    	ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
		listView.setAdapter(null);

		newTransferenceAdapterZ  =new TransferenceAdapterZ(TransferenceZurquiSummary.this,databaseHelperZ.getAllTransferenciasLines());
	  	listView.setAdapter(newTransferenceAdapterZ);
		listView.setCacheColorHint(Color.TRANSPARENT);
		listView.setSelection(INDEX);
     
    }
    
    @Override
    public void onBackPressed()
    {
        //Toast.makeText(getApplicationContext(), "Para salir debe confirmar el cierre del inventario.", Toast.LENGTH_SHORT).show();
    	/* new AlertDialog.Builder(this)
         .setTitle("Salir de la Transferencia...")
         .setMessage("Estás seguro que deseas salir de la Transferencia?")
         .setNegativeButton(android.R.string.no, null)
         .setPositiveButton(android.R.string.yes, new OnClickListener() {

             public void onClick(DialogInterface arg0, int arg1) {
            	 TransferenceItemSummary .super.onBackPressed();
             }
         }).create().show();
    	
    	 }*/
    	finish();    
    	/*  new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Salir de la Transferencia...")
        .setMessage("Está seguro que desea salir de la Transferencia??")
        .setPositiveButton("Aceptar", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();    
        }

    })
    .setNegativeButton("Cancelar", null)
    .show();*/
	 	    
   
    	
    }
	
	
	
}
