/*
 * Based on code from: 
 * http://stackoverflow.com/questions/4969053/bluetooth-connection-between-android-and-lego-mindstorm-nxt
 */
package com.example.steeringhelper;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

import android.os.Build;
import android.util.Log;

public class BT_Comm {

	//Target NXTs for communication
	final String nxt_addr = "00:16:53:13:2C:17";
	final String nxt_name = "LEJOS-OSEK";
	
	BluetoothAdapter localAdapter = BluetoothAdapter.getDefaultAdapter();
	BluetoothSocket socket_nxt = null;
	boolean success = false;
	
	private BTCommThread btc_thread;
	
	//Enables Bluetooth if not enabled
	public void enableBT(){
	    //If Bluetooth not enable then do it
		if(localAdapter == null){
			Log.d("Bluetooth", "BT adapter is null!");
			return;
		}
		
	    if(localAdapter.isEnabled()==false){
	        localAdapter.enable();
	        while(!(localAdapter.isEnabled())){
	        	Log.d("Bluetooth", "Waiting for enabling BT!");
	        }
	    }
	}
	
	public boolean isBTEnabled(){
		return localAdapter.isEnabled();
	}
	
	public void disableBT(){
		if(localAdapter.isEnabled()){
			localAdapter.disable();
		}
	}
	
	//connect to both NXTs
	public  boolean connectToNXT(){
		if(socket_nxt != null && socket_nxt.isConnected()){
			return true;
		}
		
	    //get the BluetoothDevice of the NXT
	    BluetoothDevice nxt = localAdapter.getRemoteDevice(nxt_addr);
	    Log.d("Bluetooth_nxt", nxt.getName() + ", " + nxt.getAddress());
	    //try to connect to the nxt
	    try {	
				UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
				if (Build.VERSION.SDK_INT >= 10 ) { 
					// We're trying to create an insecure socket, which is only
					// supported in API 10 and up. Otherwise, we try a secure socket
					// which is in API 7 and up.
					Log.d("Bluetooth_socket_nxt", "Try to get socket_nxt!");
					socket_nxt = nxt.createInsecureRfcommSocketToServiceRecord(uuid);
				} else {
					socket_nxt = nxt.createRfcommSocketToServiceRecord(uuid);
				} 
				Log.d("Bluetooth_socket_nxt", socket_nxt.toString());
				socket_nxt.connect();
				btc_thread = new BTCommThread(this);
				new Thread(btc_thread).start();
				success = true;
	    } catch (Exception e) {
			// TODO Auto-generated catch block
	    	success = false;
	    	Log.d("Bluetooth",e.getMessage());
		}
	    return success;
	
	}
	
	
	public boolean isNXTConnected(){
		if(socket_nxt == null){
			return false;
		}
		return socket_nxt.isConnected();
	}
	
	public void disconnectNXT(){
		if(socket_nxt == null){
			return;
		}
		if(!socket_nxt.isConnected()){
			try {
				socket_nxt.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.d("Bluetooth", e.getMessage());
			}
		}
		socket_nxt = null;
	}
	
	
	public void writeMessage(String msg) throws InterruptedException{
	    BluetoothSocket connSock;
	
	    connSock = socket_nxt;
	
	    if(connSock!=null){
	        try {
	
	            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connSock.getOutputStream()));
	            out.write(msg);
	            out.flush();
	
	            Thread.sleep(30);
	
	
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	    }else{
	        //Error
	    }
	}
	
	//assume that we only receive string commands from nxt
	public String readMessage(){
	    BluetoothSocket connSock;
	    int n;
	    connSock = socket_nxt;
	
	    if(connSock!=null){
	        try {
	
	        	BufferedReader in = new BufferedReader(new InputStreamReader(connSock.getInputStream()));
	        
	            return in.readLine();
	
	
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            Log.d("Bluetooth", e.getMessage());
	            return null;
	        }
	    }else{
	        //Error
	        return null;
	    }
	
	}
}