package com.example.bluetoothserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.UUID;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {
	static TextView textview1;
	private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	private final int REQUEST_ENABLE_BT = 2;
	private BluetoothAdapter mBluetoothAdapter = null;
	private Thread AT;
	private final static int MESSAGE_READ = 1;
	private static Handler mHandler = new Handler(){
		public void handleMessage (Message message, String str){
			if(message.what == MESSAGE_READ){
				Log.e("handler",str);
				textview1.setText(textview1.getText()+str);
			}
	
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textview1 = (TextView)findViewById(R.id.textView1);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		StartBluetooth();
		
		AT = new AcceptThread();
		AT.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	//開啟藍芽
    public void StartBluetooth(){
    	
    	
    	// 如果裝置不支援藍芽
		if (mBluetoothAdapter == null) {
			Toast.makeText(this,
			"Bluetooth is not available.",
			Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		// 如果藍芽沒有開啟
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		}
		
    }
    //bluetooth server
    private class AcceptThread extends Thread {
        private final BluetoothServerSocket mmServerSocket;
     
        public AcceptThread() {
            // Use a temporary object that is later assigned to mmServerSocket,
            // because mmServerSocket is final
            BluetoothServerSocket tmp = null;
            try {
                // MY_UUID is the app's UUID string, also used by the client code
                tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("BluetoothServer", MY_UUID);
            } catch (IOException e) { 
            	Log.e("listenUsingRfcommWithServiceRecord","error");
            }
            mmServerSocket = tmp;
        }
     
        public void run() {
            BluetoothSocket socket = null;
            // Keep listening until exception occurs or a socket is returned
            while (true) {
                try {
                    socket = mmServerSocket.accept();
                    Log.e("listen","listen");
                } catch (IOException e) {
                	Log.e("listen","listen over");
                    break;
                }
                // If a connection was accepted
                if (socket != null) {
                    // Do work to manage the connection (in a separate thread)
                	Thread CT = new ConnectedThread(socket);
                	CT.start();
                	Log.e("Connected","Connected");
                    //Log.e("socketclose","socketclose");
					//mmServerSocket.close();
                    break;
                }
            }
        }
     
        /** Will cancel the listening socket, and cause the thread to finish */
        public void cancel() {
            try {
                mmServerSocket.close();
            } catch (IOException e) { }
        }
    }
    
    private class ConnectedThread extends Thread {
        private BluetoothSocket mmSocket;
        private InputStream mmInStream;
     
        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            Log.e("a","a");
            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
            	mmInStream = socket.getInputStream();
            	Log.e("get","get");
            } catch (IOException e) { 
            	Log.e("error","error");
            }
        }
        @Override
        public void run() {
            BufferedReader br;
            String line = "";
            String tmp = "";
            br = new BufferedReader(new InputStreamReader(mmInStream));
            Log.e("br",br.toString());
            // Keep listening to the InputStream until an exception occurs
            try {
				while ((line = br.readLine())!=null) {
					MainActivity.mHandler.obtainMessage(MESSAGE_READ, line).sendToTarget();
					Log.e("line",line);
				}
				
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e("BufferedReader excrption",tmp);
				e.printStackTrace();
			}
            
			Log.e("txt",tmp);
			cancel();
        }
     
        /* Call this from the main activity to shutdown the connection */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
}
