package com.android.testbtspp2_1;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;

import com.android.Algorithm.*;
//import com.android.testbtspp2_1.*;
import com.android.MathClass.*;
import com.android.application.*;
import com.android.main.*;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class ReceivingThread3 extends Thread {
	private final String TAG = "ReceivingThread3";
    private static final boolean D = true;
	private BluetoothAdapter mBluetoothAdapter = null;
    //private BluetoothServerSocket btSocket = null;
    private BluetoothSocket btSPPSocket = null;
    private BluetoothDevice device;
    //private OutputStream outStream = null;
    private InputStream inStream = null;
    // Well known SPP UUID (will *probably* map to
    // RFCOMM channel 1 (default) if not in use);
    // see comments in onResume().
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//channel 1
    //private static final UUID MY_UUID = UUID.fromString("0000111E-0000-1000-8000-00805F9B34FB");//channel 2
    //private static final UUID MY_UUID = UUID.fromString("0000111C-0000-1000-8000-00805F9B34FB");//channel 2
    private static final String address = "00:26:5E:97:84:57";//UCSD X200s
    //private static final String address = "00:18:00:00:01:34";//headband 512
    //private static String address = "00:18:00:00:01:31";//headband 128
    //private static String address = "00:15:83:C7:38:20";//BT dongle
    private byte[] buffer;
    private boolean isStop;
    private final Handler mHandler;
    private static final int PRINTMESSAGE = 0;
    private static final int ADDCOUNT =1;
    private Lock mlock;
    private String myName;
	public ReceivingThread3(Handler handler,Lock lock,String name){
        mHandler = handler;
        mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"IN THE CREATER").sendToTarget();
        buffer = new byte[2000];
        isStop = false;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mlock = lock;
        myName = name;
	}
	public synchronized void setIsStop(boolean newtag){
		this.isStop = newtag;
	}
	public void run(){
		mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"IN THE RUN").sendToTarget();
		
       
        /*device = mBluetoothAdapter.getRemoteDevice(address); 
   	 	try {
			btSPPSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
		} catch (IOException e1) {
			mHandler.obtainMessage(PRINTMESSAGE, TAG+":IOException1, " +e1.getMessage()).sendToTarget();
		}*/
		device = mBluetoothAdapter.getRemoteDevice(address); 
   	 	Method m = null;
		try {
			m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
		} catch (SecurityException e1) {
			mHandler.obtainMessage(PRINTMESSAGE, TAG+":SecurityException, " +e1.getMessage()).sendToTarget();//tt.append("SecurityException, " +e1.getMessage());
		} catch (NoSuchMethodException e1) {
			mHandler.obtainMessage(PRINTMESSAGE, TAG+":NoSuchMethodException, " +e1.getMessage()).sendToTarget();
		} 
		try {
			btSPPSocket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1));
		} catch (IllegalArgumentException e) {
			mHandler.obtainMessage(PRINTMESSAGE, TAG+":IllegalArgumentException, " +e.getMessage()).sendToTarget();
		} catch (IllegalAccessException e) {
			mHandler.obtainMessage(PRINTMESSAGE, TAG+":IllegalAccessException, " +e.getMessage()).sendToTarget();
		} catch (InvocationTargetException e) {
			mHandler.obtainMessage(PRINTMESSAGE, TAG+":InvocationTargetException, " +e.getMessage()).sendToTarget();
		} 
  
		try {
			mHandler.obtainMessage(PRINTMESSAGE, TAG+": Waiting for CONNECT.").sendToTarget();
			btSPPSocket.connect();
			//Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");
			mHandler.obtainMessage(PRINTMESSAGE, TAG+": BT connection established, data transfer link open.").sendToTarget();
            //btSocket.close();
		} catch (IOException e) {
			closeAllSocket();
            mHandler.obtainMessage(PRINTMESSAGE, TAG+": IOException1. "+e.getMessage()).sendToTarget();
		}
	mBluetoothAdapter.cancelDiscovery();

	try {
        inStream = btSPPSocket.getInputStream();
        //inStream = btSPPSocket.getInputStream();
        mHandler.obtainMessage(PRINTMESSAGE, TAG+": INPUTSTREAM OPENED.").sendToTarget();
	} catch (IOException e) {
        //Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
        mHandler.obtainMessage(PRINTMESSAGE, TAG+": getInputStream."+e.getMessage()).sendToTarget();
	}
		int size =0;
		try {
			while(!isStop){
				//handler.sendMessage(handler.obtainMessage());
				mlock.wantToUse();
				//mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"READING FROM INPUTSTREAM,size= "+Integer.toString(size)).sendToTarget();
				//mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"SLEEP!"+inStream.available()).sendToTarget();
				//synchronized(this){
				sleep(1);
				if((size = inStream.available())==0){
					if(D)Log.i(TAG, "inStream size = 0");
					mHandler.obtainMessage(ADDCOUNT,0,0,myName).sendToTarget();
				}
				else
					mHandler.obtainMessage(ADDCOUNT,inStream.read(buffer),buffer[0],myName).sendToTarget();
				mlock.leave();
				//}
				//mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"Wake up!"+inStream.available()).sendToTarget();
			}
		} catch (IOException e) {
			mHandler.obtainMessage(PRINTMESSAGE, TAG+": IOException2, "+e.getMessage()).sendToTarget();
		} catch (InterruptedException e2){
			mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"InterruptedException").sendToTarget();
		}
		finally{
			closeAllSocket();
			mlock.leave();
			mHandler.obtainMessage(PRINTMESSAGE, TAG+" IS DONE!").sendToTarget();
		}	
		//for(int i=0;i<buffer.length;i++)
		//	mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"Buffer["+i+"]= "+(int)buffer[i]).sendToTarget();
	}
	public void closeAllSocket(){
		//mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"CLOSE ALL STREAM").sendToTarget();//tt.append("^^^^^^CLOSE ALL STREAM^^^^^^\r\n");
	   	/*if(inStream != null){
	   		try {
					inStream.close();
				} catch (IOException e) {
					mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"IOException in inStream.close()").sendToTarget();
				}
	        }*/
        if(btSPPSocket!= null){
			try {
				btSPPSocket.close();
				
			} catch (IOException e) {
				mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"IOException in btSPPSocket.close()").sendToTarget();
			}
        }
        mHandler.obtainMessage(PRINTMESSAGE, TAG+": "+"ALL STREAM CLOSED").sendToTarget();//tt.append("^^^^^^ALL STREAM CLOSED^^^^^^\r\n");
    }
}
