/*
 * Copyright 2012 Indigo Rose Software Design Corporation
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.example.waoperations.Stats;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.Normalizer;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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.bimsdk.usb.UsbConnect;
import com.bimsdk.usb.io.OnDataReceive;

import com.example.waoperations.R;
import com.example.waoperations.UserPermissionsDatabaseHelper;
import com.example.waoperations.VoiceHelper;
import com.example.waoperations.R.color;
import com.example.waoperations.R.id;
import com.example.waoperations.R.layout;
import com.example.waoperations.R.menu;


import android.animation.ObjectAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.StrictMode;
import android.os.SystemClock;
import android.os.Vibrator;


import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TypefaceSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
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.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Main UI for the demo app.
 */
public class StatsDetail extends Activity {
    public String client;
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	public int COUNTER =0;
    TextView mDisplay;
    private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
    private StatsDatabaseHelper databaseHelper;
    public String EMP,BOD,INVENTDIM,LOCATIONA,LOCATIONB,ITEMID,CONFIG,USER,COUNTINGSTARTED,QTY;
    public int tipo;
	public String Scanning="";
    public int timerstarted=0;
	public Boolean timercompleted=false;
	public int execute=0;
	public double QTYFINAL;
    final Context context = this;

    private static final String tag = "Main";



    //private static final String TAG = "DemoActivity";
    
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.place_details);
    	Intent intent = getIntent();
		EMP=intent.getStringExtra("INDEX");
		//BOD=intent.getStringExtra("BOD");
		//USER=intent.getStringExtra("USER");	
        //tipo=0;

	ActionBar actionBar = getActionBar();
	actionBar.hide();
	// more stuff here...
	    
	actionBar.setSubtitle("Stats");
	actionBar.setTitle("Warehouse");
	actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
	actionBar.setDisplayShowTitleEnabled(false);  // required to force redraw, without, gray color
	actionBar.setDisplayShowTitleEnabled(true);
	actionBar.setDisplayHomeAsUpEnabled(true);
	actionBar.show();     
    
    Typeface fontbold = Typeface.createFromAsset(this.getApplicationContext().getAssets(), "fonts/opensans-extrabold.ttf"); 

	//final TextView view =(TextView) findViewById(R.id.article);

    databaseHelper = new StatsDatabaseHelper(this.getApplicationContext()); 
    
     Cursor cursor = databaseHelper.getItemByID(EMP);
     cursor.moveToFirst();
     
	 
		 
     
	 TextView nombre =(TextView) findViewById(R.id.nombre);
	  if(cursor.getCount()>0){
	 nombre.setText(cursor.getString(2));
	 USER=cursor.getString(1);
	 TextView fecha =(TextView) findViewById(R.id.fecha);
	 fecha.setText(""+cursor.getString(3));
	 TextView operacion =(TextView) findViewById(R.id.operacion);
     if(cursor.getString(4).equals("10")||cursor.getString(4).equals("11")){
    	 operacion.setText("Recepción: "+cursor.getString(5));	
         }
         if(cursor.getString(4).equals("20")||cursor.getString(4).equals("21")){
        	 operacion.setText("Acomodo: "+cursor.getString(5));		
         }
         if(cursor.getString(4).equals("30")||cursor.getString(4).equals("31")){
        	 operacion.setText("Alisto: "+cursor.getString(5));		
         }
         if(cursor.getString(4).equals("40")||cursor.getString(4).equals("41")){
        	 operacion.setText("Envío: "+cursor.getString(5));		
         }
         if(cursor.getString(4).equals("50")||cursor.getString(4).equals("51")){
        	 operacion.setText("Inventario: "+cursor.getString(5));		
         }
         if(cursor.getString(4).equals("60")||cursor.getString(4).equals("51")){
        	 operacion.setText("Reabastecimiento: "+cursor.getString(5));		
         }
	 TextView completado =(TextView) findViewById(R.id.completado);
	
	   if(cursor.getString(6).equals("0")){
		   
	   }
	      else if(cursor.getString(4).equals("60")){
          
	    completado.setText("Pendientes: "+cursor.getString(6));
      
          }
	   else{    
           Double porcentaje=Double.valueOf(cursor.getString(7))/Double.valueOf(cursor.getString(6))*100;
           NumberFormat nf3 = NumberFormat.getInstance();
	        nf3.setMaximumFractionDigits(0);// set as you need
           completado.setText("Completado: "+cursor.getString(7)+"/"+cursor.getString(6)+"("+nf3.format(porcentaje)+"%)");

	   }
	  }
	 
	

      /* 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 = "'"+cursor.getString(1)+"'";
			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");


		  //  String v2 = "'"+BOD+"'"; 
//  		    String v3 = "'"+PO+"'"; 
///    		    String v4 = "'"+EQUIPO+"'"; 

	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	     //	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
	       	nameValuePairs.add(new BasicNameValuePair("user",v1));
	      	
	      	
	//apartir de aqui carga ruta
		try
		{
	    	        HttpClient httpclient = new DefaultHttpClient();
	    	        HttpPost httppost = new HttpPost("http://10.10.100.13/getIndividualStats.php");
	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    	        HttpResponse response = httpclient.execute(httppost); 
	    	        HttpEntity entity = response.getEntity();
	    	        is = entity.getContent();

	    	        Log.e("log_tag", "connection success ");
	    	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
		}
	catch(Exception e)
		{
	    	        Log.e("log_tag", "Error in http connection "+e.toString());
	    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
	    	//  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
		}
	    	//convert response to string
		try{
			
	    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
	    	        StringBuilder sb = new StringBuilder();
	    	        String line = null;
	    	        while ((line = reader.readLine()) != null) 
	    	        {
	    	                sb.append(line + "\n");
	    	        }
	    	        is.close();
	    	        result=sb.toString();
		}
		catch(Exception e)
		{
	    	       Log.e("log_tag", "Error converting result "+e.toString());
		}
	int counter=0;
	    	//parse json data
	    	try{
           

	    	 	JSONArray jArray = new JSONArray(result);
	    		for(int i=0;i<jArray.length();i++)  
	            {
	    			try{
	    		   	JSONObject no = jArray.getJSONObject(i);
	    		  
	    		 
	    		  String Rec=no.getString("Rec");
	    		  String Put=no.getString("Put");
	    		  String Pic=no.getString("Pic");
	      		  String Shi=no.getString("Shi");
	     		  String Inv=no.getString("Inv");
	     		  String Rep=no.getString("Rep");
	      	
	     		 TextView Rece =(TextView) findViewById(R.id.rec);
	     		Rece.setText(Rec);
	     		 TextView Puta =(TextView) findViewById(R.id.put);
	     		Puta.setText(Put);
	     		 TextView Pick =(TextView) findViewById(R.id.pic);
	     		Pick.setText(Pic);
	     		 TextView Ship =(TextView) findViewById(R.id.shi);
	     		Ship.setText(Shi);
	     		 TextView Inve =(TextView) findViewById(R.id.inv);
	     		Inve.setText(Inv);
	     		 TextView Repl =(TextView) findViewById(R.id.rep);
	     		Repl.setText(Rep);

                Double total= Double.parseDouble(Rec)+Double.parseDouble(Put)+Double.parseDouble(Pic)+Double.parseDouble(Shi)+Double.parseDouble(Rep)+Double.parseDouble(Inv);
                TextView Total =(TextView) findViewById(R.id.day);
                NumberFormat nf3 = NumberFormat.getInstance();
	 	        nf3.setMaximumFractionDigits(0);// set as you need
                Total.setText(nf3.format(total));
                
                
                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.");
		}
	  
		  new GetImageTask(getBaseContext()).execute("aca va el url");
			 
	if (!UsbConnect.isConnect(this)) {
		UsbConnect.Connect(this);
	}

    }

    @Override
 
	  @SuppressWarnings("deprecation")
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			 if (requestCode == 0) {
				    if (resultCode == RESULT_OK) {
				       final String  contents = data.getStringExtra("SCAN_RESULT"); // This will contain your scan result
		                String format = data.getStringExtra("SCAN_RESULT_FORMAT");
				    }
		 }}

    

    private class GetImageTask extends AsyncTask<String, Void, Bitmap>{
        Context mContext;
 
        public GetImageTask(Context context){
            super();
            mContext = context;
        }
 
        // Finding address using reverse geocoding
        @Override
        protected Bitmap doInBackground(String... params) {
           
            String url = params[0];
            
            String abc="http://10.10.100.13/img/"+USER+".jpg";
            
            Bitmap bitmap = DownloadImage(abc
  		            );
            
            return bitmap;
        }
 
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            // Setting the title for the marker.
            // This will be displayed on taping the marker
            //markerOptions.title(addressText);
        
        	   if(bitmap!=null){
  		        RelativeLayout img = (RelativeLayout) findViewById(R.id.clientimage);
  		        img.setBackground(new BitmapDrawable(bitmap));}
            // Placing a marker on the touched position
         //   googleMap.addMarker(markerOptions);
 
        }
    }
    
    
    private InputStream OpenHttpConnection(String urlString)
    	    throws IOException
    	    {
    	        InputStream in = null;
    	        int response = -1;
    	                 
    	        URL url = new URL(urlString);
    	        URLConnection conn = url.openConnection();
    	                   
    	        if (!(conn instanceof HttpURLConnection))                    
    	            throw new IOException("Not an HTTP connection");
    	          
    	        try{
    	            HttpURLConnection httpConn = (HttpURLConnection) conn;
    	            httpConn.setAllowUserInteraction(false);
    	            httpConn.setInstanceFollowRedirects(true);
    	            httpConn.setRequestMethod("GET");
    	            httpConn.connect();
    	  
    	            response = httpConn.getResponseCode();                
    	            if (response == HttpURLConnection.HTTP_OK) {
    	                in = httpConn.getInputStream();                                
    	            }                    
    	        }
    	        catch (Exception ex)
    	        {
    	            throw new IOException("Error connecting");           
    	        }
    	        return in;    
    	        
    	        
    	    }
    	
    private Bitmap DownloadImage(String URL)
    	    {       
    	        Bitmap bitmap = null;
    	        InputStream in = null;       
    	        try {
    	            in = OpenHttpConnection(URL);
    	            bitmap = BitmapFactory.decodeStream(in);
    	            in.close();
    	        } catch (IOException e1) {
    	            // TODO Auto-generated catch block
    	            e1.printStackTrace();
    	        }
    	        return bitmap;               
    	    }


    
    

}
