
package com.android.main;
//http://www.anddev.org/serial_over_bluetooth_simple_test_client-t11106.html
//This version could connect two headbands, however,
//	1.no Lock.java be used.
//	2.Only one stream could receive data.
//	3.Can't open 3rd stream, the program will crash.
/**
 * 2011/02/28, BUG: The range of specific frequency should be adjustable itself
 */

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

import com.android.application.PowerDensityandSkullmapActivity;
import com.android.main.Buffer;
import com.android.main.Lock;
import com.android.main.ReceivingThread;
import com.android.main.TimeDomainActivity;
import com.android.multiStimuli.OpenGLES.MultiStimuli_OpenGLES_Activity;
import com.android.testbtspp2_1.TestViewActivity;
import com.android.Stimuli.*;
import com.android.Stimuli.OpenGL.*;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ToggleButton;

public class main extends Activity implements View.OnClickListener,CheckBox.OnCheckedChangeListener{
	
	 //private static final UUID SERIAL_PORT_SERVICE_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  private static final String TAG = "MAIN";
  private static final boolean D = true;
  private TextView tt;
  private Button btnEXIT,btnCLEAR,btnChangeIntent,btnChangeIntentToMain;
  private CheckBox linkCheckBox,linkCheckBox2,linkCheckBox3;
  private ReceivingThread rThread;
  private Lock lock;
  private CheckBox tSwitcher1,tSwitcher2,tSwitcher3;
  private int hb1count,hb2count,hb3count;
  private BluetoothAdapter mBluetoothAdapter;
  private boolean isBluetoothEnable;
  private Buffer buffer;
  private AnimationDrawable f,f2;
  private ToggleButton tbButton;
  //private Intent canvasIntent;
  //protected DemoView demoview;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       tt= (TextView)findViewById(R.id.text);
       btnEXIT = (Button)findViewById(R.id.stopButton);
       btnCLEAR = (Button)findViewById(R.id.clearButton);
       btnChangeIntent = (Button)findViewById(R.id.changeToCanvasIntentButton);
       //btnChangeIntentToMain = (Button)findViewById(R.id.ButtonBackToMain);
       tSwitcher1 = (CheckBox)findViewById(R.id.HB1Count);
       //tSwitcher2 = (CheckBox)findViewById(R.id.HB2Count);
       //tSwitcher3 = (CheckBox)findViewById(R.id.HB3Count);
       //btnChangeIntentToMain.setOnClickListener(this);
       btnEXIT.setOnClickListener(this);
       btnCLEAR.setOnClickListener(this);
       btnChangeIntent.setOnClickListener(this);
       tSwitcher1.setOnCheckedChangeListener(this);
       //linkCheckBox = (CheckBox)findViewById(R.id.linkCheck);
       //linkCheckBox.setOnCheckedChangeListener(this);
       /*linkCheckBox2 = (CheckBox)findViewById(R.id.link2Check);
       linkCheckBox2.setOnCheckedChangeListener(this);
       linkCheckBox2.setClickable(false);
       linkCheckBox3 = (CheckBox)findViewById(R.id.link3Check);
       linkCheckBox3.setOnCheckedChangeListener(this);
       linkCheckBox3.setClickable(false);*/
       lock = new Lock();
       hb1count=0;
       hb2count=0;
       hb3count=0;
       mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
       isBluetoothEnable = false;
       buffer = new Buffer();//sample rate is 128,final static!
       //canvasIntent = new Intent(this, Canvas.class);
       /*if((isBluetoothEnable = initialBluetooth()) == false){
     	  tt.append(TAG+" Bluetooth not ready!!! \r\n");
     	  //linkCheckBox.setClickable(false);
     	  //linkCheckBox2.setClickable(false);
       }*/
       tbButton = (ToggleButton) findViewById(R.id.ConnectionONOFF);
       tbButton.setOnClickListener(this);
    	   
  }
  private boolean initialBluetooth(){
 	 boolean tag = true;
 	 if (mBluetoothAdapter != null) {
	         if (!mBluetoothAdapter.isEnabled()) {
	        	 tt.append(TAG+":Please enable your BT and re-run this program");
	        	 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    
	        	 startActivityForResult(enableBtIntent, 1);//REQUEST_ENABLE_BT);
	        	 tag = false;
	         }
      }
 	 return tag;
  }
  private final Handler mHandler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
          switch (msg.what) {
          case 0://print message
         	 tt.append((String)msg.obj+"\r\n");
         	 break;
          case 1://add count
         	 if(((String)msg.obj).equalsIgnoreCase("HB1"))
         		 tSwitcher1.setText(Integer.toString(++hb1count)+",Ava:"+msg.arg1+" ,Read:"+msg.arg2);
         	 else if(((String)msg.obj).equalsIgnoreCase("HB2"))
         		 tSwitcher2.setText(Integer.toString(++hb2count)+",Ava:"+msg.arg1+" ,Read:"+msg.arg2);
         	 else
         		 tSwitcher3.setText(Integer.toString(++hb3count)+",Ava:"+msg.arg1+" ,Read:"+msg.arg2);
         	 break;
          case 2://fill in buffer, called from ReceivingThread
         	 //new a FillInBufferThread
         	 //put data into buffer
         	 //
         	 //FillInBufferThread a = new FillInBufferThread(mHandler, new byte[1], Buffer);
         	 break;
          }
      }
  };
  @Override
  public void onStart() {
       super.onStart();
       if (D){
            Log.e(TAG, "++ ON START ++");
       }
       /*ImageView img = (ImageView)findViewById(R.id.simple_anim);
       //img.setImageResource(R.drawable.whitesquare);
       img.setBackgroundResource(R.anim.squareanimation);
       //img.setVisibility(View.VISIBLE);
       f = (AnimationDrawable) img.getBackground(); 
       //f.setCallback(img);
       //f.setVisible(true, true);
       img.post(new Stater());
       
       ImageView img2 = (ImageView)findViewById(R.id.simple_anim2);
       img2.setBackgroundResource(R.anim.squareanimation);
       //img2.setVisibility(View.VISIBLE);
       f2 = (AnimationDrawable) img2.getBackground(); 
       //f2.setCallback(img);
       //f2.setVisible(true, true);
       img2.post(new Stater2());
       */
       //f.start();
       //Log.e(TAG, Integer.toString(f.getNumberOfFrames()));
  }
  class Stater2 implements Runnable{
	  public void run(){
		  f2.start();
	  }
  }
  class Stater implements Runnable{
	  public void run(){
		  f.start();
	  }
  }
  
  @Override
  public void onResume() {
       super.onResume();
       System.gc();
       if (D) {
            Log.e(TAG, "+ ON RESUME +");
       }
       /*if(rThread!=null){
     	  rThread.setIsStop(true);
     	  rThread = null;
       }
       if(rThread2 != null){
     	  rThread2.setIsStop(true);
     	  rThread2 = null;
       }*/
  }

  @Override
  public void onPause() {
       super.onPause();
       if (D){
            Log.e(TAG, "- ON PAUSE -");
       }
       //closeAllSocket();
  }

  @Override
  public void onStop() {
       super.onStop();
       if (D){
            Log.e(TAG, "-- ON STOP --");
       }
       /*if(rThread!=null){
     	  rThread.setIsStop(true);
     	  rThread = null;
       }
       if(rThread2 != null){
     	  rThread2.setIsStop(true);
     	  rThread2 = null;
       }*/
  }
  
  @Override
  public void onDestroy() {
       super.onDestroy();
       if (D){
            Log.e(TAG, "--- ON DESTROY ---");
            tt.append(TAG+"--- ON DESTROY ---");
       }
       if(rThread!=null){
     	  rThread.setIsStop(true);
     	  rThread = null;
       }
       finish();
  }
	public void onClick(View arg0) {
		//closeAllSocket();
		//if(D)Log.e(TAG, Integer.toString(arg0.getId()));
		if(R.id.clearButton == arg0.getId()){
			if(D)Log.e(TAG, "clearButton pressed");
			tt.setText("");
			buffer.saveRawDataToFile();
			//startActivity(new Intent(main.this,TestViewActivity.class));
		}
		else if(arg0.getId() == R.id.changeToCanvasIntentButton){
			if(D)Log.e(TAG, "CanvasButton pressed");
			//demoview = new DemoView(this, 128, buffer);
			//setContentView(demoview);
			tt.append("CanvasButton pressed\n");
			//startActivity(new Intent(main.this, MultiStimuli_OpenGLES_Activity.class));
			startActivity(new Intent(main.this,Stimuli_OpenGL_Activity.class));
			//startActivity(new Intent(testbtspp2_1.this,PowerDensityandSkullmapActivity.class));
			//startActivity(new Intent(testbtspp2_1.this,FrequencyDomainActivity.class));
		}
		else if(arg0.getId() == R.id.HB1Count){
			if(D)Log.e(TAG, "HB1Count pressed");
			tt.append("HB1Count pressed\n");
			//startActivity(new Intent(testbtspp2_1.this, Swipe.class));
			//startActivity(new Intent(this, SlideSample.class));
		}
		else if(arg0.getId() == R.id.ConnectionONOFF){
			if (tbButton.isChecked()) {            
				if(rThread == null){
					rThread = new ReceivingThread(mHandler,lock,"HB1");
					rThread.start();
					tt.append(TAG+": "+"ReceivingThread start!\r\n");
				}
 		   } 
 		   else {            
 			  if(rThread.isAlive()){
					tt.append(TAG+": "+"Receivinthread is alive, killing it!\r\n");
					rThread.setIsStop(true);
					//rThread.closeAllSocket();
				}
 			  else{
					tt.append(TAG+": "+"Receivinthread is dead!\r\n");
 			  }
				//rThread.stop();
				rThread = null;        
				tt.append("***************\r\n");
 		   }   
		}
		else{
			onDestroy();
		}
		
	}

	public void onCheckedChanged(CompoundButton arg0, boolean checked) {
		/*if(R.id.linkCheck == arg0.getId()){//headband1
			if(checked){
				linkCheckBox.setText("Connecting...");
				if(rThread == null){
					rThread = new ReceivingThread(mHandler,lock,"HB1");
					rThread.start();
					tt.append(TAG+": "+"ReceivingThread start!\r\n");
				}
			}
			else{
				linkCheckBox.setText("Disconnected...");//set to NO
				if(rThread.isAlive()){
					tt.append(TAG+": "+"Receivinthread is alive, killing it!\r\n");
					rThread.setIsStop(true);
					//rThread.closeAllSocket();
				}
				else{
					tt.append(TAG+": "+"Receivinthread is dead!\r\n");
				}
				//rThread.stop();
				rThread = null;
			}
		}
		else*/ if(R.id.HB1Count == arg0.getId()){
			if(checked){
				//buffer.saveRawDataToFile();
				//buffer.closeStream();
				//tt.append(TAG+": "+"**************DATA SAVED**************");
				//startActivity(new Intent(testbtspp2_1.this, Swipe.class));
				//startActivity(new Intent(this, TimeDomainActivity.class));
			}
		}
		/*else if(R.id.link2Check == arg0.getId()){//headband2
			if(checked){
				linkCheckBox2.setText("L2: YES");
				if(rThread2 == null){
					rThread2 = new ReceivingThread2(mHandler,lock,"HB2");
					rThread2.start();
					tt.append(TAG+": "+"ReceivingThread2 start!\r\n");
				}
			}
			else{
				linkCheckBox2.setText("L2: NO");
				if(rThread2.isAlive()){
					tt.append(TAG+": "+"Receivinthread2 is alive, killing it!\r\n");
					rThread2.setIsStop(true);
					rThread2.closeAllSocket();
				}
				else{
					tt.append(TAG+": "+"Receivinthread2 is dead!\r\n");
				}
				//rThread2.stop();
				rThread2 = null;
			}
		}*/
		else{
			tt.append(TAG+": Buffer size: "+buffer.getDataIndex()+"\r");
			/*if(checked){
			linkCheckBox3.setText("L3: YES");
			if(ranThread == null){
				ranThread = new RandomNumberThread(mHandler);
				ranThread.start();
				tt.append(TAG+": "+"RandomNumberThread start!\r\n");
			}
			}
			else{
				linkCheckBox3.setText("L3: NO");
				if(ranThread.isAlive()){
					tt.append(TAG+": "+"RandomNumberThread is alive, killing it!\r\n");
					ranThread.setIsStop(true);
				}
				else{
					tt.append(TAG+": "+"RandomNumberThread is dead!\r\n");
				}
				//rThread3.stop();
				ranThread = null;
			}*/
			/*if(checked){
				linkCheckBox3.setText("L3: YES");
				if(rThread3 == null){
					rThread3 = new ReceivingThread3(mHandler,lock,"HB3");
					rThread3.start();
					tt.append(TAG+": "+"ReceivingThread3 start!\r\n");
				}
			}
			else{
				linkCheckBox3.setText("L3: NO");
				if(rThread3.isAlive()){
					tt.append(TAG+": "+"Receivinthread3 is alive, killing it!\r\n");
					rThread3.setIsStop(true);
					rThread3.closeAllSocket();
				}
				else{
					tt.append(TAG+": "+"Receivinthread3 is dead!\r\n");
				}
				//rThread3.stop();
				rThread3 = null;
			}*/
		}
	}
}
/**
package com.android.main;

import android.app.Activity;
import android.os.Bundle;

public class main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
*/