/**
 * This thread runs during a connection with a remote device.
 * It handles all incoming and outgoing transmissions.
 */
package nctu.brc.mindo_con.bluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import mindo.connect.Mindo_connect;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

public class ControlThread implements Runnable{
	public static final int Channel_Data = 1;
	public static final int Data_Lost = 2;
    private static final UUID btUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");	
    private BluetoothDevice btDevice; 								
    private BluetoothSocket btSocket;								
    private InputStream btInStream;									
    private OutputStream btOutStream;
    private Mindo_connect mindo_connect;
    public static final boolean NONE = false;			
    public static final boolean CONNECTED = true;  		
    public boolean btState;
    public static int filter_selected=0,changeGain_selected=0,changeGain_num=0;
    private Handler mHandler;
    private int Resolution,Channel,SampleRate,Gain,pre_dataLost=-1;
    
   public ControlThread(Handler mHandler, BluetoothDevice btDevice, int resolution, int channel, int srate, int gain) {       
        this.mHandler = mHandler;
        this.btDevice = btDevice;    
        this.Resolution = resolution;
        this.Channel = channel;
        this.SampleRate = srate;
        this.Gain = gain; 
        Log.v("info", String.valueOf(Resolution)+","+String.valueOf(Channel)+","+String.valueOf(SampleRate)+","+String.valueOf(Gain));
      
        
        
        connectBT();
        
    }
   
    @Override
	public void run(){
    	
    	if(btState == NONE){
    		releaseAllResources();
    		return;
    	}		
    
        while (btState == CONNECTED){
            	
            													
					double[] rcvData = mindo_connect.getMindoData();
					for(int i=0;i<Channel;i++){
						mHandler.obtainMessage(Channel_Data, -1,i,(float)rcvData[i]).sendToTarget();    
					}
					
					int dataLost = mindo_connect.getDataLostCount();
					
					if(pre_dataLost!=dataLost){
						mHandler.obtainMessage(Data_Lost, dataLost,-1,-1).sendToTarget();  
						pre_dataLost = dataLost;
					}
					
				
				
				if(filter_selected == 1){
					boolean state = mindo_connect.NotchFilter_on();
            		filter_selected = 0;
            	}
            	
            	if(filter_selected ==  2){
            		boolean state = mindo_connect.NotchFilter_off();           		
            		filter_selected = 0;
            	}
            	if(changeGain_selected == 1){
            		Gain = changeGain_num;
            		
            		boolean state = mindo_connect.Change_Gain(Gain);
            		changeGain_selected = 0;
            	}
       
        	
        }
        
        releaseAllResources();
    }

    public void releaseAllResources() {
    	    	
    	if(btSocket!=null){
    		
		    try {	
		    	mindo_connect.parseStopCommand();
		    	btInStream.close();
		    	btOutStream.close();
		    	btSocket.close();
		    } catch (IOException e) {}

    	}
    }
    
   
    public boolean connectBT()
    {         
        try {
        	btSocket = btDevice.createRfcommSocketToServiceRecord(btUUID);
        } catch (IOException e) {     	
            return false;
        }   	   	
       
        try {    	
        	btSocket.connect();
        	btOutStream = btSocket.getOutputStream();    
        	btInStream = btSocket.getInputStream();
        	mindo_connect = new Mindo_connect(Resolution,Channel,SampleRate,Gain,btOutStream,btInStream);
        	mindo_connect.parseStartCommand();       	
        } catch (IOException e) {       	
			return false;
        }
      
      
    	btState = CONNECTED;
        return true;
    }

	public synchronized void onExit(){
    	btState = NONE;
    }
    public synchronized void onConnect(){
    	btState = CONNECTED;
    }   
}