package com.android.testbtspp2_1;
import java.util.Vector;

import android.os.Handler;
import android.util.Log;
import com.android.Algorithm.*;
//import com.android.testbtspp2_1.*;
import com.android.MathClass.*;
import com.android.application.*;
import com.android.main.*;
public class DrawCCAThread extends Thread {
	private Handler mHandler;
	private Vector tempVector;
	private boolean DEBUG = true;
	private String TAG = "DrawCCAThread";
	private Buffer buffer;
	private boolean STOPTAG;
	public DrawCCAThread(Handler handler, String index){
		mHandler = handler;
		tempVector = new Vector(4);
		buffer = new Buffer();
		STOPTAG = false;
		TAG+=index;
	}
	public void setStopTag(boolean tag){
		STOPTAG = tag;
	}
	public void run(){
		while(!STOPTAG){//
			//for(int i=0;i<20;i++){			
			tempVector.removeAllElements();
			/*for(int i=0;i<1000;i++){
				mHandler.obtainMessage(1, i).sendToTarget();//fill in data
				try {
					sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}*/
			tempVector = buffer.getData4();
			if(getMean()){//check if size==4, and get the mean of Vector
				mHandler.obtainMessage(1, tempVector).sendToTarget();//fill in data
				if(DEBUG)Log.e(TAG, "set data to CCAdomainActivity");	
			}
			try {
					sleep(1000);
			} catch (InterruptedException e) {
					e.printStackTrace();
			}
		}
	}
	public void run1(){
		double[]temp = new double[128];
		for(int j=0;j<128;j++){
			temp[j]	= Math.sin(j * 2 *  Math.PI * 9 / 128);//+0.2*Math.sin(j * 2 *  Math.PI * (Math.random()*50) / 128);
			//temp[j]	=Math.sin(j * 2 *  Math.PI * (Math.random()*50) / 128);
		}
		while(true){//for(int i=0;i<1000;i++){			
			tempVector.add(temp);
			tempVector.add(temp);
			tempVector.add(temp);
			tempVector.add(temp);
			mHandler.obtainMessage(1, tempVector).sendToTarget();//fill in data
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			tempVector.removeAllElements();
		}
	}
	private boolean getMean(){
		boolean tag = true;
		if(tempVector.size()!=4){
			tag = false;
			return tag;
		}
		double[]temp1 = (double[])tempVector.elementAt(0);
		double[]temp2 = (double[])tempVector.elementAt(1);
		double[]temp3 = (double[])tempVector.elementAt(2);
		double[]temp4 = (double[])tempVector.elementAt(3);
		int sum1 = 0;
		int sum2 = 0;
		int sum3 = 0;
		int sum4 = 0;
		for(int i=0;i<temp1.length;i++){
			sum1+=temp1[i];
			sum2+=temp2[i];
			sum3+=temp3[i];
			sum4+=temp4[i];
		}
		sum1 = sum1 / temp1.length;
		sum2 = sum2 / temp2.length;
		sum3 = sum3 / temp3.length;
		sum4 = sum4 / temp4.length;
		for(int i=0;i<temp1.length;i++){
			temp1[i]-=sum1;
			temp2[i]-=sum2;
			temp3[i]-=sum3;
			temp4[i]-=sum4;
		}
		tempVector.clear();
		tempVector.add(temp1);
		tempVector.add(temp2);
		tempVector.add(temp3);
		tempVector.add(temp4);
		return tag;
	}
}
