package com.example.waoperations.Aduanas;

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 org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.waoperations.R;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;

import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AduanasSummary extends Activity {
	
	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    public String PO,EMP;
    TextView mDisplay;
    public String almacen = "GRUPO CAROSSI A200";
    AduanasAdapter newAduanasAdapter;
    private ProgressDialog progressDialog;
    private SwipeRefreshLayout swipeRefreshLayout;
    private AduanasDatabaseHelper databaseHelper;
    //private static final String TAG = "DemoActivity";
    
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aduanaslist);
        
       // final TextView txt =(TextView) findViewById(R.id.Titulo);
        View header = getLayoutInflater().inflate(R.layout.generalheader, null);
        TextView HeaderName = (TextView) header.findViewById(R.id.tableroheader);
    	Intent intent = getIntent();
		PO=intent.getStringExtra("PO");
		EMP=intent.getStringExtra("EMP");
		//BOD=intent.getStringExtra("BOD");
		//USER=intent.getStringExtra("USER");
    	
    	HeaderName.setText("Posición: " +PO);
    	HeaderName.setTextSize(26);
    	
	    ListView listView = (ListView)findViewById(R.id.aduanaslistview);
	
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    
	    actionBar.setSubtitle("Consulta Aduanas");
	    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(newAduanasAdapter);
	    listView.setCacheColorHint(Color.TRANSPARENT);
	    databaseHelper = new AduanasDatabaseHelper(this.getApplicationContext()); 
		databaseHelper.deleteAllData();
			
 	    new LoadViewTask().execute();   
	
		newAduanasAdapter = new AduanasAdapter(this.getApplicationContext(),databaseHelper.getAllAduanasLines(PO));
	  	listView.setAdapter(newAduanasAdapter);

    }
   
    
    private class LoadViewTask extends AsyncTask<Void, Integer, Void>  
    {  //Before running code in separate thread  
   
        @Override  
        protected void onPreExecute()  
        {  
        	progressDialog = ProgressDialog.show(AduanasSummary.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 result = null;
            	InputStream is = null;
            	String v1 = "'"+EMP+"'";
            	String v2 = "'"+PO+"'";
            	
        		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
        	
            	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
            	nameValuePairs.add(new BasicNameValuePair("UID",v2));
             
        //apartir de aqui carga ruta
        	try
        	{
            	        HttpClient httpclient = new DefaultHttpClient();
            	        HttpPost httppost = new HttpPost("http://10.10.100.13/getAduanasListCc.php");
            	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            	        HttpResponse response = httpclient.execute(httppost); 
            	        HttpEntity entity = response.getEntity();
            	        is = 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(is,"ISO-8859-1"),8);
            	        StringBuilder sb = new StringBuilder();
            	        String line = null;
            	        while ((line = reader.readLine()) != null) 
            	        {
            	                sb.append(line + "\n");
            	        }
            	        is.close();
            	        result=sb.toString();
        	}
        	catch(Exception e)
        	{
            	       Log.e("log_tag", "Error converting result "+e.toString());
        	}
        	
        int counter=0;
        
            	//parse json data
            	try{
                    databaseHelper.deleteAllData();

            	 	JSONArray jArray = new JSONArray(result);
            		for(int i=0;i<jArray.length();i++)  
                    {
            			try{
				            		   	JSONObject no = jArray.getJSONObject(i);
				            		   	
				            		   	String itemid=no.getString("ITEMID");
				            		    String merdescription=no.getString("MERDESCRIPTION");
				            		   	String qty=no.getString("QTY");
				            		    String ownername=no.getString("OWNERNAME");
				            		    String netweight=no.getString("NETWEIGHT");
				            		    String bl=no.getString("BL");
				            		    String configid=no.getString("CONFIGID");
				            		    String yearid=no.getString("YEARID");
				            		    String documentnumber=no.getString("DOCUMENTNUMBER");
				            		    String custominventoryid=no.getString("CUSTOMINVENTORYID");
				            		    String entrancedate=no.getString("ENTRANCEDATE");

				        	            NumberFormat nf = NumberFormat.getInstance();
				        	            nf.setMaximumFractionDigits(0);// set as you need
				                      
				        	            databaseHelper.saveAduanasLine( itemid, merdescription, qty, almacen, ownername, netweight,bl, configid, yearid,documentnumber,custominventoryid,entrancedate,PO);
				        	            
				        	            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.");
        	}
			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  tView)findViewById(R.id.aduanaslistview);
            progressDialog.dismiss();  
        		
    			Cursor x =databaseHelper.getAllAduanasLines(PO);
            	if(x.getCount()==0){
               Toast.makeText(getBaseContext(), "No hay unidades por contar.", Toast.LENGTH_LONG).show();	
            	}      
            	ListView listView = (ListView)findViewById(R.id.aduanaslistview);
        		listView.setAdapter(null);

        		newAduanasAdapter =new AduanasAdapter(AduanasSummary.this,databaseHelper.getAllAduanasLines(PO));
    		  	listView.setAdapter(newAduanasAdapter);
    			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);
        		//
            }
    
    }
  
    
    private class LoadViewTaskRefresh extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  
   
        @Override  
        protected void onPreExecute()  
        {  
        	/*progressDialog = ProgressDialog.show(AduanasSummary.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 result = null;
            	InputStream is = null;
            	String v1 = "'"+EMP+"'";
            	String v2 = "'"+PO+"'";
        		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
        	
            	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
            	nameValuePairs.add(new BasicNameValuePair("UID",v2));
            	
             
        //apartir de aqui carga ruta
        	try
        	{
            	        HttpClient httpclient = new DefaultHttpClient();
            	        HttpPost httppost = new HttpPost("http://10.10.100.13/getAduanasListCc.php");
            	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            	        HttpResponse response = httpclient.execute(httppost); 
            	        HttpEntity entity = response.getEntity();
            	        is = 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(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 id=no.getString("itemidaux");
				            		   	String itemid=no.getString("ITEMID");
				            		    String merdescription=no.getString("MERDESCRIPTION");
				            		   	String qty=no.getString("QTY");
				            		    String ownername=no.getString("OWNERNAME");
				            		    String netweight=no.getString("NETWEIGHT");
				            		    String bl=no.getString("BL");
				            		    String configid=no.getString("CONFIGID");
				            		    String yearid=no.getString("YEARID");
				            		    String documentnumber=no.getString("DOCUMENTNUMBER");
				            		    String custominventoryid=no.getString("CUSTOMINVENTORYID");
				            		    String entrancedate=no.getString("ENTRANCEDATE");

				        	            NumberFormat nf = NumberFormat.getInstance();
				        	            nf.setMaximumFractionDigits(0);// set as you need
				                      
				        	            databaseHelper.saveAduanasLine(itemid, merdescription, qty, almacen, ownername, netweight,bl, configid, yearid,documentnumber,custominventoryid,entrancedate,PO);
				        	            
				        	            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.");
        	}
			return null;
        	
        }
        
         //after executing the code in the thread  
        @Override  
        protected void onPostExecute(Void result)  
        {  
            //close the progress dialog  tView)findViewById(R.id.aduanaslistview);
            progressDialog.dismiss();  

    			Cursor x =databaseHelper.getAllAduanasLines(PO);
            	if(x.getCount()==0){
               Toast.makeText(getBaseContext(), "No hay unidades por contar.", Toast.LENGTH_LONG).show();	
            	}      
            	
          		ListView listView = (ListView)findViewById(R.id.aduanaslistview);
        		listView.setAdapter(null);
        		        		
        		newAduanasAdapter =new AduanasAdapter(AduanasSummary.this,databaseHelper.getAllAduanasLines(PO));
    		  	listView.setAdapter(newAduanasAdapter);
    			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
    	
	    /*	int id = item.getItemId();
	    	if (id == R.id.pickpath)
	    	{
	    		
	    		/*Intent intento = new Intent(getApplicationContext() ,AduanasDetail.class);
	        	intento.putExtra("PO", PO);
	       	    intento.putExtra("EX","0"); 
	      	    intento.putExtra("DATA",EMP); 
	      	    intento.putExtra("USER",USER); 
	    	    startActivity(intento);
	
	    	} else if (id == R.id.upload) {
	    		//Cï¿½digo alternativo
	    	}*/
                    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.aduanaslistview);
		 	listView.setAdapter(null);
		 	newAduanasAdapter = new AduanasAdapter(this.getApplicationContext(),databaseHelper.getAllAduanasLines(PO));
		  	listView.setAdapter(newAduanasAdapter);
			listView.setCacheColorHint(Color.TRANSPARENT);
        }
    
    @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 Consulta...")
         .setMessage("Estás seguro que deseas salir de la consulta?")
         .setNegativeButton(android.R.string.no, null)
         .setPositiveButton(android.R.string.yes, new OnClickListener() {

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

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