package com.example.wireless;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.*;
import android.content.Context;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;


public class ConnectThread extends Thread{
	private BluetoothSocket mmSocket;
	private BluetoothDevice mmDevice;
	
    public ConnectThread() {
    	BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    	BluetoothDevice b = adapter.getRemoteDevice("C8:19:F7:FD:07:12");
    	BluetoothSocket tmp = null;
        mmDevice = b;
        try {
        	//a60f35f0-b93a-11de-8a39-08002009c666
        	//00001101-0000-1000-8000-00805F9B34FB
        	UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = b.createRfcommSocketToServiceRecord(uuid);
        } catch (IOException e) { Log.d("TRANSFER", e.toString());}
        mmSocket = tmp;
    
    }
	
    public void run() {
    	
    	Log.d("TRANSFER", "Client thread started");
        // Cancel discovery because it will slow down the connection
    	
        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
        	double startTime = System.nanoTime();
            mmSocket.connect();
            double endTime = System.nanoTime();
    		double duration = endTime - startTime;
    		 Log.d("TRANSFER", "Latency :"+(duration)+"secs.");
            Log.d("TRANSFER", "Client connected!");
            
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }
 
        // Do work to manage the connection (in a separate thread)
        manageConnectedSocket(mmSocket);
    }
    
    public void manageConnectedSocket(BluetoothSocket socket)
	{
    	Log.d("TRANSFER", "Managing socket from Client");
    	Thread t = new Thread(new ConnectedThread(socket, true));
    	t.start();
    	//t.write(byteString);
	}
 
    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
    
    public void message()
    {
    	Transfer t = new Transfer();
    	Context context = t.getContext();
    	CharSequence text = "Hello toast!";
    	int duration = Toast.LENGTH_SHORT;

    	Toast toast = Toast.makeText(context, text, duration);
    	toast.show();
    }

}
