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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.Normalizer;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import 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 com.example.waoperations.Stats.StatsDatabaseHelper;


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.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
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.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.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 ReplenishmentDetail 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 ReplenishmentDatabaseHelper databaseHelper;
    public String EMP,BOD,INVENTDIM,LOCATIONA,LOCATIONB,ITEMID,CONFIG,USER,COUNTINGSTARTED,QTY,ID,BARCODE,ROUTEID;
    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.wareplenishmentitem);
    	Intent intent = getIntent();
		EMP=intent.getStringExtra("DATA");
		BOD=intent.getStringExtra("BOD");
		USER=intent.getStringExtra("USER");	
		ID=intent.getStringExtra("INDEX");	
        tipo=0;

	ActionBar actionBar = getActionBar();
	actionBar.hide();
	// more stuff here...
	    
	actionBar.setSubtitle("Replenishment");
	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();     
	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	COUNTINGSTARTED = sd.format(new Date()); 
	
    Typeface fontbold = Typeface.createFromAsset(this.getApplicationContext().getAssets(), "fonts/opensans-extrabold.ttf"); 

	final TextView viewfrom =(TextView) findViewById(R.id.buscarheader);

	viewfrom.setOnClickListener(new View.OnClickListener() {
    //When you click the button, Alert dialog will be showed
    public void onClick(View v) {
   /* Alert Dialog Code Start*/ 	
   	 if(COUNTER==0){
    	AlertDialog.Builder alert = new AlertDialog.Builder(context);
    	alert.setTitle("Posición de origen"); //Set Alert dialog title here
    	alert.setMessage("Digite posición de origen"); //Message here

        // Set an EditText view to get user input 
        final EditText input = new EditText(context);
        alert.setView(input);

    	alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    	public void onClick(DialogInterface dialog, int whichButton) {
    	 //You will get as string input data in this variable.
    	 // here we convert the input to a string and show in a toast.
    	 String srt = input.getEditableText().toString();
    		//TextView PO = (TextView) header.findViewById(R.id.position);
    		//PO.setText(srt);
		
			
			   TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
	     	    if(srt.equals(buscarheader.getText().toString().trim())){
	     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
       	        COUNTER++;
	     	    }else{
	     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
	     	    }
				  
    	 
    	} // End of onClick(DialogInterface dialog, int whichButton)
    }); //End of alert.setPositiveButton
    	alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
    	  public void onClick(DialogInterface dialog, int whichButton) {
    	    // Canceled.
    		  dialog.cancel();
    	  }
    }); //End of alert.setNegativeButton
    	AlertDialog alertDialog = alert.create();
    	alertDialog.show();
   /* Alert Dialog Code End*/        
 }

   	 // End of onClick(View v)
    }
});
	
    
    
	final TextView view =(TextView) findViewById(R.id.article);

	view.setOnClickListener(new View.OnClickListener() {
    //When you click the button, Alert dialog will be showed
    public void onClick(View v) {
   /* Alert Dialog Code Start*/ 	
   
   	 if(COUNTER==1){
     	AlertDialog.Builder alert = new AlertDialog.Builder(context);
     	alert.setTitle("Validación de ítem"); //Set Alert dialog title here
     	alert.setMessage("Digite ítem"); //Message here

         // Set an EditText view to get user input 
         final EditText input = new EditText(context);
         alert.setView(input);

     	alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
     	public void onClick(DialogInterface dialog, int whichButton) {
     	 //You will get as string input data in this variable.
     	 // here we convert the input to a string and show in a toast.
     	 String srt = input.getEditableText().toString();
     		//TextView PO = (TextView) header.findViewById(R.id.position);
     		//PO.setText(srt);

      	    TextView buscarheader = (TextView) findViewById(R.id.article);
     	    if(srt.equals(buscarheader.getText().toString().trim())){
     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
     	    COUNTER++;  
     	    }else{
         	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
     	    }
                 		
 				  
     	 
     	} // End of onClick(DialogInterface dialog, int whichButton)
     }); //End of alert.setPositiveButton
     	alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
     	  public void onClick(DialogInterface dialog, int whichButton) {
     	    // Canceled.
     		  dialog.cancel();
     	  }
     }); //End of alert.setNegativeButton
     	AlertDialog alertDialog = alert.create();
     	alertDialog.show();
    /* Alert Dialog Code End*/        
  }
   	 
   	 
   	 
   	 
   	 // End of onClick(View v)
    }
});
	

	if (!UsbConnect.isConnect(this)) {
		UsbConnect.Connect(this);
	}
	
	
	 databaseHelper = new ReplenishmentDatabaseHelper(this.getApplicationContext()); 
	    
     Cursor cursor = databaseHelper.getItemByID(ID);
     cursor.moveToFirst();
     TextView fromloc = (TextView) findViewById(R.id.buscarheader);
     TextView article = (TextView) findViewById(R.id.article);
     TextView toloc = (TextView) findViewById(R.id.toheader);
     TextView ofqty = (TextView) findViewById(R.id.ofqty);
	  if(cursor.getCount()>0){
	 fromloc.setText(cursor.getString(2));
	 article.setText(cursor.getString(3));
	 toloc.setText(cursor.getString(4));
	 ofqty.setText(cursor.getString(5)+" "+cursor.getString(6));
	 BARCODE=cursor.getString(9);
	 
	  }
	
	

    }



	  @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");
				    }
		 }}

   
  
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	
    	execute=1;
	    	

        String key = KeyEvent.keyCodeToString(keyCode);
        // key will be something like "KEYCODE_A" - extract the "A"
        // use pattern to convert int keycode to some character
        Matcher matcher = KEYCODE_PATTERN.matcher(key);
        
        if (matcher.matches()) {
            // append character to textview
        	 Scanning=Scanning+matcher.group(1);
        //	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
          //
        }
        // let the default implementation handle the event
     
		new CountDownTimer(1000, 1000) {       
			   public void onTick(long millisUntilFinished) {          
			     
			}       

			public void onFinish() {   
				if(execute==1){
				execute=0;
				
				if(COUNTER==0){
					   TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
			     	    if(Scanning.equals(buscarheader.getText().toString().trim())){
			     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
	            	    COUNTER++;
			     	    }else{
			     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
			     	    }
				  }
				  else if(COUNTER==1){
					    TextView buscarheader = (TextView) findViewById(R.id.article);
			     	    if(Scanning.equals(BARCODE)){
			     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
			     	    COUNTER++;  
			     	    }else{
			         	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
			     	    }
				  }
				//Aca carga la ubicacion objetivo
				  else if(COUNTER==2){
			     	    TextView buscarheader = (TextView) findViewById(R.id.toheader);
			     	    if(Scanning.equals(buscarheader.getText().toString().trim())){
			     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
			     	    COUNTER++;  
			     	    }else{
			     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));		
			     	    }
				  }
            	Scanning="";
		        }
			  }
			}.start();  
 
        return super.onKeyDown(keyCode, event);
    }
    
	   public void onComplete(View view) {  
			
	         if(COUNTER==0){
	       	Toast.makeText(getApplicationContext(), "Escanee o digite ubicación de partida.", Toast.LENGTH_SHORT).show();
			   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
			   intentemoslo.putExtra("voz","Escanee o digite la ubicación de partida");  
			   startService(intentemoslo);	
				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            	// Vibrate for 400 milliseconds
            	v.vibrate(400);
	         }
	         if(COUNTER==1){
			       	Toast.makeText(getApplicationContext(), "Escanee o digite el artículo.", Toast.LENGTH_SHORT).show();	 
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","Escanee o digite el artículo");  
	     			   startService(intentemoslo);	
	     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                	// Vibrate for 400 milliseconds
	                	v.vibrate(400);
	         }
	         if(COUNTER==2){
			       	Toast.makeText(getApplicationContext(), "Escanee o digite la ubicación de destino.", Toast.LENGTH_SHORT).show();	 
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","Escanee o digite la ubicación de destino");  
	     			   startService(intentemoslo);	
	     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                	// Vibrate for 400 milliseconds
	                	v.vibrate(400);
	         }
	         
	       
	         if(COUNTER==3){  
	        	 databaseHelper = new ReplenishmentDatabaseHelper(this.getApplicationContext()); 
	     	    
	             Cursor cursor = databaseHelper.getItemByID(ID);
	             cursor.moveToFirst();
	 				try{

		 			 	String result = null;
		 			 	InputStream is = null;
		        		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			    		String dat = sd.format(new Date()); 
			    		
		 			 	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		 			 	ROUTEID=cursor.getString(12);
		 			  	nameValuePairs.add(new BasicNameValuePair("TID","'"+cursor.getString(12)+"'"));
		 			 	nameValuePairs.add(new BasicNameValuePair("FROM","'"+cursor.getString(2)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("TO","'"+cursor.getString(4)+"'"));
		 			  	nameValuePairs.add(new BasicNameValuePair("ITEMID","'"+cursor.getString(3)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("QTY","'"+cursor.getString(5)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("TYPE","'"+cursor.getString(6)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("INVENTDIMID","'"+cursor.getString(13)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("ACTIVATIONDATE","'"+cursor.getString(11)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("TRANSDATE","'"+dat+"'"));
                        nameValuePairs.add(new BasicNameValuePair("TRANSDATEBEGIN","'"+COUNTINGSTARTED+"'"));
                        nameValuePairs.add(new BasicNameValuePair("COUNTEDBY","'"+USER+"'"));
                        nameValuePairs.add(new BasicNameValuePair("EMP","'"+EMP+"'"));

                        
		 			    StrictMode.setThreadPolicy(policy); 
		 			    //http post
		 			    try{
		 			        	        HttpClient httpclient = new DefaultHttpClient();
		 			        	        HttpPost httppost = new HttpPost("http://10.10.100.13/UpdateReplenishmentList.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){}
		 					        	
		 			
	 				
	 				
	 			   try{
		       		 	 String result = null;
		       		 	InputStream is = null;
		  		     	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		       		 	nameValuePairs.add(new BasicNameValuePair("ROUTEID","'"+ROUTEID+"'"));
		       		    nameValuePairs.add(new BasicNameValuePair("Warehouse","'"+"BOD_01"+"'"));
		       		    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/UpdateProcessedReplenishment.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{
		       		        		if(result.equals("[]\n")){    Toast toasta=Toast.makeText(getApplicationContext(), "Refresque la pantalla.", 2000);
		    			  	        toasta.setGravity(Gravity.CENTER,0,0);
		    			  	        toasta.show();}else{
		       		        	            	JSONObject json_data = new JSONObject(result);
		       		        	                CharSequence w= (CharSequence) json_data.get("re");
		       		        	  			    Toast toasta=Toast.makeText(getApplicationContext(), w, 2000);
		       						  	        toasta.setGravity(Gravity.CENTER,0,0);
		       						  	        toasta.show();	}
		       		        	     }
		       		        	catch(JSONException e)
		       		        	   {
		       		        	        Log.e("log_tag", "Error parsing data "+e.toString());
		       		        	        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
		       		        	    }}catch(Exception e){}

	 				
		 	      	Toast.makeText(getApplicationContext(), "Reabastecimiento registrado.", Toast.LENGTH_SHORT).show();	 
					Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			intentemoslo.putExtra("voz","Reabastecimiento registrado");  
	       
	     			try {
	     		
	     			} catch (Exception e) {
	     			    e.printStackTrace();
	     			}
	     			startService(intentemoslo);	
	     	
	     			 finish();   

	 		 }
	 		else
	 		{	
	 		}
	    }


}
