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


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 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 InventoryAddBarcode 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)");
    InventoryAdapter newInventoryAdapter;
    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 InventoryDatabaseHelper databaseHelper;
    //private static final String TAG = "DemoActivity";
    
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.waaddbarcodeitem);
    	Intent intent = getIntent();
		EMP=intent.getStringExtra("EMP");
		BOD=intent.getStringExtra("BOD");
		USER=intent.getStringExtra("USER");	
        tipo=0;

	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    
	actionBar.setSubtitle("Inventory");
	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"); 
	
    
    String[] paises = new String[]{"und","B6","B10","B11","B12","B2","B250","B3","B4","B48","B5","B7","B8","B9","DR","PL"};
	Spinner equipment = (Spinner) findViewById(R.id.configuracion);
	ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, paises);
	
	// Specify the layout to use when the list of choices appears
	adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	// Apply the adapter to the spinner
	equipment.setAdapter(adapter2);
	final TextView view =(TextView) findViewById(R.id.buscarheader);

	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==0){
    	AlertDialog.Builder alert = new AlertDialog.Builder(context);
    	alert.setTitle("Selecció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.buscarheader);
            buscarheader.setText(srt);
    	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
            ITEMID=srt;
    	    	try {
    	    	} catch (Exception e) {
    	    	    e.printStackTrace();
    	    	}
    	    COUNTER++;   		
				  
    	 
    	} // 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)
    }
});
	
	GetData();
	if (!UsbConnect.isConnect(this)) {
		UsbConnect.Connect(this);
	}

    }



	  @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){

				  }

				else if(COUNTER==1){
	          	    TextView buscarheader = (TextView) findViewById(R.id.barcode);
                    buscarheader.setText(Scanning);
            	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
                     LOCATIONA=Scanning;
            	    	try {
            	    	} catch (Exception e) {
            	    	    e.printStackTrace();
            	    	}
            	    COUNTER++;  
				  }

				
            	Scanning="";
		    }}
	 
			   
			}.start();  
 
        return super.onKeyDown(keyCode, event);
    }
    
	private void GetData() {
		
		//Receive data from bluetooth scanner
		Scanning="";
	
		UsbConnect.SetOnDataReceive(new OnDataReceive() {
			@Override
			public void DataReceive(byte[] data , boolean flg) {
				  Scanning=Scanning+new String(data).trim();
					 
				  if(timerstarted==0&&(Scanning.equals("")==false)){
					  timerstarted=1;
				 	new CountDownTimer(300, 300) {       
						   public void onTick(long millisUntilFinished) {          
						}       

						public void onFinish() {  timercompleted=true; 	
						if(timercompleted==true){	
				
				
			  if(Scanning.equals("")){}
			  else{
					if(execute==1){
						execute=0;
						
						if(COUNTER==0){
				          	    TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
		                        buscarheader.setText(Scanning);
			            	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
			                     LOCATIONA=Scanning;
			            	    	try {
			            	    	} catch (Exception e) {
			            	    	    e.printStackTrace();
			            	    	}
			            	    COUNTER++;
						  }else if(COUNTER==1){
							 	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
								COUNTINGSTARTED = sd.format(new Date()); 

					     		int itemsfound=0;
						     	    StrictMode.setThreadPolicy(policy); 
						     		try{
						    				
						    			String result = null;
						    	        InputStream is = null;
						    	      
						    	        String v1 = "'"+EMP+"'";
						    	    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
						    	    	String v2 = "'BOD_01'";
						    			String v3 = "'"+Scanning+"'"; 
						    			String v4 = "'"+LOCATIONA+"'"; 

						    	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
						    	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
						    	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
						    	        nameValuePairs.add(new BasicNameValuePair("UID",v3));
						    	        nameValuePairs.add(new BasicNameValuePair("posicion",v4));
						    	        
						           	//apartir de aqui carga ruta
						    	  	try
						    	   	{
						    	        	        HttpClient httpclient = new DefaultHttpClient();
						    	        	        HttpPost httppost = new HttpPost("http://10.10.100.13/getInventoryPerItemAndLocation.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(), "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");
						    	        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
						    	        	        }
						    	        	        is.close();
						    	        	        result=sb.toString();
						    	   	}
						    	   	catch(Exception e)
						    	   	{
						    	        	       Log.e("log_tag", "Error converting result "+e.toString());
						    	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
						    	   	}
						    	int counter=0;
						    	        	//parse json data
						    	        	try{
					                            double totalqty=0;
					                            
						    	        	 	JSONArray jArray = new JSONArray(result);
						    	        		for(int i=0;i<jArray.length();i++)  
						    		        {
						    	        			itemsfound++;
						    	        			counter++;
						    	        			try{
						    	        		   	JSONObject no = jArray.getJSONObject(i);    
						    	        		    String sku=no.getString("itemID");
						    	        		
						    	        		    
						    	        	        String qty2=no.getString("qty");
						    	        		    try{
						    	        		    Double Qt = Double.parseDouble(qty2);
						    	        		    NumberFormat nf = NumberFormat.getInstance();
						    		 	            nf.setMaximumFractionDigits(0);// set as you need
						    		 	            QTYFINAL=QTYFINAL+Qt;
						    		 	            
						    		 	           qty2=nf.format(Qt).replace(",", "");
						    	        		    }catch(Exception e){}
						    	        		    
						    	        		    
						    	        		    
						    	        		    String idim=no.getString("inventdim");
						    	        		    String config=no.getString("dim");
						    	        		    CONFIG=config;
						    	        		    ITEMID=sku;
						    	        		    INVENTDIM=idim;
					                                
						    	 	            	}
						    	        	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.");
						    	        	}
						     		if(itemsfound==0){
							     	    TextView buscarheader = (TextView) findViewById(R.id.article);
							             buscarheader.setText("");
							     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));

						     		}else{
						     	    TextView buscarheader = (TextView) findViewById(R.id.article);
					             buscarheader.setText(ITEMID);
					     	    buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
					     	     TextView qty = (TextView) findViewById(R.id.ofqty);
					     	    NumberFormat nf = NumberFormat.getInstance();
						            nf.setMaximumFractionDigits(0);// set as you need
						           QTY=nf.format(QTYFINAL);
							     qty.setText("de "+QTYFINAL+" "+CONFIG);	 
					               COUNTER++;	
						     		}
							  
						  }
						//Aca carga la ubicacion objetivo
						  else if(COUNTER==2){
					     	    TextView buscarheader = (TextView) findViewById(R.id.toheader);
		                        buscarheader.setText(Scanning);
			            	    	buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));
			              	        LOCATIONB=Scanning;
			            	    	EditText myEditText = (EditText) findViewById(R.id.qtyamount);
			                        myEditText.setClickable(true);
			                        myEditText.setFocusable(true);
			                        myEditText.setFocusableInTouchMode(true);
			                        myEditText.requestFocus();     
			          
			            	    COUNTER++;  
		  
						  }
		            	Scanning="";
				    }
				
                timerstarted=0;
	      	      Scanning="";
	      	      timercompleted=false;
				
			}
						}
		}}.start();  
}
			
			}	
		});

	}
 
	public void onComplete(View view) {  
			
	         if(COUNTER==0){
	       	Toast.makeText(getApplicationContext(), "Digite ítem.", Toast.LENGTH_SHORT).show();
			   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
			   intentemoslo.putExtra("voz","Digite el artículo.");  
			   startService(intentemoslo);	
				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            	// Vibrate for 400 milliseconds
            	v.vibrate(400);
	         }
	         if(COUNTER==1){
			       	Toast.makeText(getApplicationContext(), "Escanee el código de barras.", Toast.LENGTH_SHORT).show();	 
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","Escanee el código de barras");  
	     			   startService(intentemoslo);	
	     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                	// Vibrate for 400 milliseconds
	                	v.vibrate(400);
	         }else{
	        	   Boolean TERMINUS=false;
	        	 try{
	        		 String TYPE="";
	        		 try{
	        			Spinner TIPOS = (Spinner)findViewById(R.id.configuracion);
			 	         TYPE = TIPOS.getSelectedItem().toString();
	        		 }catch(Exception e){}
		 			 	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>();
		 			  
		 			  	//SUBE ON HAND NO DIFERENCIA
		 			 	nameValuePairs.add(new BasicNameValuePair("ITEM","'"+ITEMID+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("CODE","'"+LOCATIONA+"'"));
		 			  	nameValuePairs.add(new BasicNameValuePair("TYPE","'"+TYPE+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("TRANSDATE","'"+dat+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("TRANSDATEBEGIN","'"+dat+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("USER","'"+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/UpdateBarcode.php");
		 			        	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		 			        	        HttpResponse response = httpclient.execute(httppost); 
		 			        	        HttpEntity entity = response.getEntity();
		 			        	        is = entity.getContent();
		 			        	        Log.e("log_tag", "connection success ");
		 			        	        TERMINUS=true;
		 			        	      //  Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
		 			        	   }
		 			        	catch(Exception e)
		 			        	{
		 			        	    TERMINUS=false;
		 			        	        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){}
		 					        	
		 			if(TERMINUS)	{	        
		 	      	Toast.makeText(getApplicationContext(), "Código ingresado.", Toast.LENGTH_SHORT).show();	 
					Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			intentemoslo.putExtra("voz","Código ingresado");  

	     			try {
	     		
	     			} catch (Exception e) {
	     			    e.printStackTrace();
	     			}
	     			startService(intentemoslo);	
	     	
	     			  this.recreate();		  
		 			}
	 		 }
	        	 
	        	 
	        	 
	        	 
	        	 
	         

	         
	       
	 		
	         }
				  
	    
private boolean hasContent(EditText et) {
		       return (et.getText().toString().trim().length() > 0);
		}

    
    

}
