package com.BBST.intelligentes_haus;

import java.util.ArrayList;
import android.os.Bundle;
import android.os.Parcelable;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
//import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.bluetooth.*;


public class Start extends Activity
{
	//private ArrayAdapter<String> mArrayAdapter;
	private BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
	private ArrayList<BluetoothDevice> mGeraeteListe = new ArrayList<BluetoothDevice>();
	int anzGeraete;
	
	private final BroadcastReceiver bluetoothState = new BroadcastReceiver()
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			//String prevStateExtra = BluetoothAdapter.EXTRA_PREVIOUS_STATE;
			String stateExtra = BluetoothAdapter.EXTRA_STATE;
			int state = intent.getIntExtra(stateExtra, -1);
			//int previousState = intent.getIntExtra(prevStateExtra, -1);
			String toastTxt = "";
			switch(state)
			{
				case(BluetoothAdapter.STATE_TURNING_ON) :
				{
					toastTxt = "Schalte Bluetooth ein.";
					Toast.makeText(Start.this, toastTxt, Toast.LENGTH_SHORT).show();
					break;
				}
				case(BluetoothAdapter.STATE_ON) :
				{
					toastTxt = "Bluetooth eingeschaltet.";
					Toast.makeText(Start.this, toastTxt, Toast.LENGTH_SHORT).show();
					Bluetooth_on();
					break;
				}
				case(BluetoothAdapter.STATE_TURNING_OFF) :
				{
					toastTxt = "Schalte Bluetooth aus ";
					Toast.makeText(Start.this, toastTxt + "und beende App.", Toast.LENGTH_SHORT).show();
					break;
				}
				case(BluetoothAdapter.STATE_OFF) :
				{
					toastTxt = "Bluetooth ausgeschaltet.";
					Toast.makeText(Start.this, toastTxt, Toast.LENGTH_SHORT).show();
					Bluetooth_on();
					break;
				}
			
			}
			
			bluetooth.startDiscovery();
			anzGeraete = 0;
			String action = intent.getAction();
	        // wenn durch die Suche ein Gerät gefunden wurde
	        if (BluetoothDevice.ACTION_FOUND.equals(action))
	        {
	            // das Bluetooth-Gerät aus dem Intent holen
	            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	            /* Hinzufügen des Namens und der Adresse in ein Array
	            mGeraeteListe.add(device);
	            anzGeraete ++;
	            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());*/
	            if(device.getAddress().equals("00066645B745"))
                {
                	Toast.makeText(Start.this, "Haus wurde gefunden.", Toast.LENGTH_LONG).show();
                	finish();
                }
                else
                {
                	Toast.makeText(Start.this, "Haus wurde nicht gefunden.", Toast.LENGTH_LONG).show();
                }
	        }
	        else
	        {
	            if(BluetoothDevice.ACTION_UUID.equals(action)) 
	            {
	              BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	              Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
	              for (int i=0; i<uuidExtra.length; i++)
	              {
	            	  Log.d("Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString(),"GEFUNDENES HANDY...");
	              }
	            }
	            else
	            {
	            	if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) 
	            	{
	                    Log.d("Discovery Started...", "CHECK FOR DEVICES");
	            	}
		            else 
		            {
		            	if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
		            	{
			            	for(int x = 0; x < mGeraeteListe.size(); x++)
			            	{
			                    
			            	}
		            	}
		            }
	            }
	        }
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start);
		Bluetooth_on();
		
		//Register the BroadcastReceiver
	    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
	    filter.addAction(BluetoothDevice.ACTION_UUID);
	    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
	    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
	    registerReceiver(bluetoothState, filter); // Don't forget to unregister during onDestroy
	}
	
	
	
	public void Bluetooth_on()
	{
		
		if(bluetooth != null)
		{
			bluetooth.setName("Hauscontroller");
			String status;
			if (bluetooth.isEnabled()) 
			{
				try 
				{
					Thread.sleep(1000);
                } 
				catch (InterruptedException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
			    String mydeviceaddress = bluetooth.getAddress();
			    String mydevicename = bluetooth.getName();
			    status = mydevicename + " : " + mydeviceaddress;
			    finish();
			    Toast.makeText(this, status, Toast.LENGTH_LONG).show();
			    Intent next = new Intent(Start.this, MainMenu.class);
			    startActivity(next);
			}
			else 
			{
				String actionRequestEnable = BluetoothAdapter.ACTION_REQUEST_ENABLE;
				String actionStateChanged = BluetoothAdapter.ACTION_STATE_CHANGED;
				IntentFilter filter = new IntentFilter(actionStateChanged);
				registerReceiver(bluetoothState, filter);
				startActivityForResult(new Intent(actionRequestEnable), 0);
			}
		}
		
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		   if (resultCode == Activity.RESULT_OK) 
		   {
		      // Bluetooth ist aktiv.
		   } 
		   else 
		   {
		      // Bluetooth wurde nicht aktiviert.
			   Toast.makeText(Start.this, "Bluetooth wurde nicht erlaubt!", Toast.LENGTH_SHORT).show();
			   finish();
		   }
		}
	
	@Override
	protected void onDestroy() 
	{
		super.onDestroy();
		unregisterReceiver(bluetoothState);
	}
	
	/*@Override
	public boolean onTouch(View v, MotionEvent event) {
		int aktion = event.getAction();
		
		if(aktion == MotionEvent.ACTION_DOWN)
		{
			touchX = (int) event.getX();
			touchY = (int) event.getY();
		}
		
		if(aktion == MotionEvent.ACTION_UP)
		{
			int tx = (int) event.getX();
			int ty = (int) event.getY();
			
			if( (touchX - tx) > 50)
			{
				//nach links
			}
			else if( (touchX - tx) <= 50)
			{
				//nach rechts
			}
			
			if( (touchY - ty) > 50)
			{
				//nach oben
				Intent intt = new Intent(Start.this, MainMenu.class);
				startActivity(intt);
				finish();
			}
			else if( (touchY - ty) <= 50)
			{
				//nach unten
				finish();
			}
		}
		
		return true;
	}*/
}
