package com.example.wireless;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

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

public class AcceptThread extends Thread {
	public BluetoothServerSocket mmServerSocket;
	public BluetoothServerSocket mmServerSocket1;
	private InputStream instream;
	private OutputStream outstream;
	private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	 
	public AcceptThread(String a)
	{
		
		BluetoothServerSocket tmp = null;

		try {
        	adapter = BluetoothAdapter.getDefaultAdapter();
        	//Set<BluetoothDevice> devices = adapter.getBondedDevices();
        	UUID uuid = UUID.fromString(a);//Generating a random UUID
        	//This UUID must be in HEX
            tmp = adapter.listenUsingRfcommWithServiceRecord("DeviceTest1", uuid);
        } catch (IOException e) { Log.d("TRANSFER", e.toString());}
        
        mmServerSocket = tmp;
	}
	
	public void run()
	{
		Log.d("TRANSFER", "Server thread started");
		BluetoothSocket socket = null;
		boolean flag = true;
		while (flag) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                break;
            }
            if (socket != null) {
                // Do work to manage the connection (in a separate thread)
            	Log.d("TRANSFER", "Server accepted connection");
                manageConnectedSocket(socket);
                try {mmServerSocket.close();}
                catch (IOException e){}
                break;
            }
            
            /*
           
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                break;
            }
            if (socket != null) {
                // Do work to manage the connection (in a separate thread)
            	Log.d("TRANSFER", "Server accepted another connection");
                manageConnectedSocket(socket);
                //try {mmServerSocket.close();}
                //catch (IOException e){}
                //break;
            }*/
            
        }
		
	}
	
	public void manageConnectedSocket(BluetoothSocket socket)
	{
		Log.d("TRANSFER", "Managing socket from server");
		Log.d("TRANSFER", socket.toString());
		Thread t = new Thread(new ConnectedThread(socket, false));
		t.start();
	}
	public void cancel()
	{
		try {
            mmServerSocket.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();
    }

}
