package com.android.testbtspp2_1;

import java.util.Vector;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.FloatMath;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;

import com.android.Algorithm.*;
//import com.android.testbtspp2_1.*;
import com.android.MathClass.*;
import com.android.application.*;
import com.android.main.*;
public class DemoView extends View implements View.OnTouchListener, View.OnLongClickListener{
	private Paint paint;
	private double[] ch1,ch2,ch3,ch4;
	private int[]xCorx;
	private int sampleRate,shiftYAxis,shiftXAxis;
	private DrawTimeDomainThread dtThread;
	private Vector tempvector;
	private boolean DEBUG = true;
	private String TAG = "DemoView";
	private Buffer mybuffer;
	private int yScale;
	private String msgToDisplay = "";
	private Toast popMsg;
	private float oriDistanceOfFingers;
	private int selectionForNextDisplay;
	private float oriXAxis;//for one finger, swipe screen
	public DemoView(Context context,int sRate){
		super(context);
		sampleRate = sRate;
		paint = new Paint();
		paint.setStyle(Paint.Style.FILL);
		paint.setStrokeWidth(2);
		paint.setColor(Color.GREEN);
		ch1 = new double[sampleRate*6];
		ch2 = new double[sampleRate*6];
		ch3 = new double[sampleRate*6];
		ch4 = new double[sampleRate*6];
		xCorx = new int[sampleRate*6];
		for (int i=0;i<sampleRate*6;i++){
			xCorx[i] = i;
		}
		dtThread = new DrawTimeDomainThread(mHandler);
		dtThread.start();
		shiftYAxis = 50;
		shiftXAxis = 0;
		tempvector = new Vector(4);
		yScale = 30;
		setOnTouchListener(this);
		setLongClickable(true);
		setOnLongClickListener(this);
		popMsg = new Toast(getContext());
		oriDistanceOfFingers = 0;
		selectionForNextDisplay = -1;//initial, should be set by longClick
		oriXAxis = 0;
	}
	/*
	 * 
	 */
	private void setData(Vector v){
		if(v.size()>=4){
			double []a = (double[])v.elementAt(0);
			double []b = (double[])v.elementAt(1);
			double []c = (double[])v.elementAt(2);
			double []d = (double[])v.elementAt(3);
			for(int i=shiftXAxis,j=0; j<a.length;i++,j++){
                  if ((a[j] / yScale + 50) > 100)
                      a[j] = yScale * 50;
                  else if ((a[j] / yScale + 50) < 0)
                      a[j] = yScale * ( -50);
                  else
                	  ch1[i] = a[j]/yScale+50;
                  
                  if ((b[j] / yScale + 150) > 200)
                      b[j] = yScale * 50;
                  else if ((b[j] / yScale + 150) < 100)
                      b[j] = yScale * -50;
                  else
                	  ch2[i] = b[j] / yScale +150;

                  if ((c[j] / yScale + 250) > 300)
                      c[j] = yScale * 50;
                  else if ((c[j] / yScale + 250) < 200)
                      c[j] = yScale * -50;
                  else
                	  ch3[i] = c[j] / yScale +250;

                  if ((d[j] / yScale + 350) > 400)
                      d[j] = yScale * 50;
                  else if ((d[j] / yScale + 350) < 300)
                      d[j] = yScale * -50;	
                  else
                	  ch4[i] = d[j] / yScale + 350;
				/*ch1[i] = a[j];
				ch2[i] = b[j];
				ch3[i] = c[j];
				ch4[i] = d[j];*/
			}
			shiftXAxis+=128;
			if(shiftXAxis>=768)
				shiftXAxis=0;
			invalidate();
		}
		if(DEBUG)Log.e(TAG, "SETTING, x="+shiftXAxis);
		//System.out.println("IN SETTING: "+shiftXAxis+"\r");
	}
	
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);	
		//shiftYAxis = (int) (100*Math.random());
		
		for (int i=0;i<ch1.length-1;i++){
			paint.setColor(Color.RED);
			canvas.drawLine((int)xCorx[i],(int)ch1[i],(int)xCorx[i+1],(int)ch1[i+1],paint);
			paint.setColor(Color.GREEN);
			canvas.drawLine((int)xCorx[i],(int)ch2[i],(int)xCorx[i+1],(int)ch2[i+1],paint);
			paint.setColor(Color.BLUE);
			canvas.drawLine((int)xCorx[i],(int)ch3[i],(int)xCorx[i+1],(int)ch3[i+1],paint);
			paint.setColor(Color.WHITE);
			canvas.drawLine((int)xCorx[i],(int)ch4[i],(int)xCorx[i+1],(int)ch4[i+1],paint);
			
		}
		paint.setColor(Color.GRAY);
		canvas.drawLine((float)shiftXAxis,(float)0,(float)shiftXAxis,(float)getHeight(),paint);
		//canvas.drawText(Integer.toString(shiftXAxis)+"/"+Integer.toString(mybuffer.getDataIndex())+"/"+msgToDisplay, 100, 100, paint);
		if(DEBUG)Log.e(TAG, "PAINTING!");
		//Log.e("onDraw", "******************"+Integer.toString(getHeight())+"**"+Integer.toString(getWidth()));
		
	}
	private final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0://repaint            	
            	invalidate();
           	 break;
            case 1://fill in data
            	tempvector = (Vector)msg.obj;
            	setData(tempvector);
           	 break;
            case 2:
           	 break;
            }
        }
    };
	public boolean onTouch(View v, MotionEvent e) {
		handleTwoFingers(e);
		handleOneFingerSwipt(e);
		/*if(e.getX()>400 ){
			msgToDisplay = "222222";
		}
		else if (e.getX()<400 ){
			msgToDisplay = Float.toString(e.getX());
		}
		//msgToDisplay = Float.toString(event.getX());*/
		return false;//if return true, the onLongClick can't work.
	}
	public boolean onLongClick(View v) {
		//msgToDisplay = "11111111111";
		new AlertDialog.Builder(this.getContext())
        //.setIcon(R.drawable.alert_dialog_icon)
        .setTitle(R.string.app_name)
        .setSingleChoiceItems(R.array.select_dialog_items2, 0, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	switch(whichButton){
            	case 0:
            		selectionForNextDisplay = 0;//button 1 pressed, Time mode display
            		break;
            	case 1:
            		selectionForNextDisplay = 1;//button 2 pressed, Frequency mode display
            		break;
            	case 2:
            		selectionForNextDisplay = 2;//button 3 pressed, CCA display
            		break;
            	case 3:
            		selectionForNextDisplay = 3;//button 4 pressed, Debug mode
            		break;
            	}
            }
        })
        .setPositiveButton(R.string.timeDomainDialog_button_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	if(selectionForNextDisplay !=-1){
            		msgToDisplay = "selectionForNextDisplay"+"/pressed";
            	}
            	selectionForNextDisplay =-1;//in case user didn't press any of mode to display, and press OK/CANCEL only.
            }
        })
        .setNegativeButton(R.string.timeDomainDialog_button_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	msgToDisplay += "3/";	
                // User clicked No so do some stuff 
            }
        })
       .show();
		return true;
	}
	private void handleOneFingerSwipt(MotionEvent event){
		int action = event.getAction();
		int actionCode = action & MotionEvent.ACTION_MASK;
		if(actionCode == MotionEvent.ACTION_POINTER_DOWN && event.getPointerCount()==1){
			oriXAxis = event.getX();
		}
		if(actionCode == MotionEvent.ACTION_MOVE &&event.getPointerCount()==1){
			if(event.getX()>oriXAxis){//swipe to right
				
			}
			else{//swipe to left
				
			}
		}
	}
	private void handleTwoFingers(MotionEvent event) {
		float newDistanceOfFingers;
		int action = event.getAction();
		int actionCode = action & MotionEvent.ACTION_MASK;
		if(actionCode == MotionEvent.ACTION_POINTER_DOWN && event.getPointerCount()==2){
			oriDistanceOfFingers = FloatMath.sqrt((event.getX(0)-event.getX(1)) * (event.getX(0)-event.getX(1)) + 
					(event.getY(0)-event.getY(1)) * (event.getY(0)-event.getY(1)));
			//Log.e("******","ori= "+oriDistanceOfFingers);
		}
		if(actionCode == MotionEvent.ACTION_MOVE &&event.getPointerCount()==2){
			newDistanceOfFingers = FloatMath.sqrt((event.getX(0)-event.getX(1)) * (event.getX(0)-event.getX(1)) + 
					(event.getY(0)-event.getY(1)) * (event.getY(0)-event.getY(1)));
			//Log.e("******","new= "+newDistanceOfFingers);
			if(newDistanceOfFingers < oriDistanceOfFingers){
				yScale +=2;
				msgToDisplay = "Zoom Out";	
				//popMsg.makeText( this.getContext(), R.string.ZoomOut_text,popMsg.LENGTH_SHORT).show();
				//Log.e("******","CCCCCCCCCc");
			}
			else{
				yScale -=2;
				msgToDisplay = "Zoom In";
				//popMsg.makeText(getContext(), R.string.ZoomIn_text,popMsg.LENGTH_SHORT).show();
				//Log.e("******","DDDDDDDDDD");
			}
		}
	}
	private void dumpEvent2(MotionEvent event) {
		   String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" ,
		      "POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" };
		   StringBuilder sb = new StringBuilder();
		   int action = event.getAction();
		   int actionCode = action & MotionEvent.ACTION_MASK;
		   sb.append("event ACTION_" ).append(names[actionCode]);//DOWN/UP/MOVE....
		   if (actionCode == MotionEvent.ACTION_POINTER_DOWN
		         || actionCode == MotionEvent.ACTION_POINTER_UP) {
		      sb.append("(pid " ).append(
		      action >> MotionEvent.ACTION_POINTER_ID_SHIFT);//ID
		      sb.append(")" );
		   }
		   sb.append("[" );
		   for (int i = 0; i < event.getPointerCount(); i++) {
		      sb.append("#" ).append(i);
		      sb.append("(pid " ).append(event.getPointerId(i));
		      sb.append(")=" ).append((int) event.getX(i));
		      sb.append("," ).append((int) event.getY(i));
		      if (i + 1 < event.getPointerCount())
		         sb.append(";" );
		   }
		   sb.append("]" );
		   Log.e(TAG, sb.toString());
	}
}

// custom drawing code here
// remember: y increases from top to bottom
// x increases from left to right
/*int x = 0;
int y = 0;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);

// make the entire canvas white
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// another way to do this is to use:
// canvas.drawColor(Color.WHITE);

// draw a solid blue circle
paint.setColor(Color.BLUE);
canvas.drawCircle(20, 20, 15, paint);

// draw blue circle with antialiasing turned on
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
canvas.drawCircle(60, 20, 15, paint);

// compare the above circles once drawn
// the fist circle has a jagged perimeter
// the second circle has a smooth perimeter

// draw a solid red rectangle
paint.setAntiAlias(false);
paint.setColor(Color.RED);

// create and draw triangles
// use a Path object to store the 3 line segments
// use .offset to draw in many locations
// note: this triangle is not centered at 0,0
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setColor(Color.RED);
Path path = new Path();
path.moveTo(0, 50);
path.lineTo(0, 100);//right down conor
//path.lineTo(-50, 0);//left down conor
path.close();
path.offset(10, 40);
canvas.drawPath(path, paint);
path.offset(50, 100);
canvas.drawPath(path, paint);
// offset is cumlative
// next draw displaces 50,100 from previous
path.offset(50, 100);
canvas.drawPath(path, paint);

// draw some text using STROKE style
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.MAGENTA);
paint.setTextSize(30);
canvas.drawText("Style.STROKE", 75, 75, paint);

// draw some text using FILL style
paint.setStyle(Paint.Style.FILL);
//turn antialiasing on
paint.setAntiAlias(true);
paint.setTextSize(30);
canvas.drawText("Style.FILL", 75, 110, paint);

// draw some rotated text
// get text width and height
// set desired drawing location
x = 75;
y = 185;
paint.setColor(Color.GRAY);
paint.setTextSize(25);
String str2rotate = "Rotated!";

// draw bounding rect before rotating text
Rect rect = new Rect();
paint.getTextBounds(str2rotate, 0, str2rotate.length(), rect);
canvas.translate(x, y);
paint.setStyle(Paint.Style.FILL);
// draw unrotated text
canvas.drawText("!Rotated", 0, 0, paint);
paint.setStyle(Paint.Style.STROKE);
canvas.drawRect(rect, paint);
// undo the translate
canvas.translate(-x, -y);

// rotate the canvas on center of the text to draw
canvas.rotate(-45, x + rect.exactCenterX(),
                                   y + rect.exactCenterY());
// draw the rotated text
paint.setStyle(Paint.Style.FILL);
canvas.drawText(str2rotate, x, y, paint);

//undo the rotate
canvas.restore();
canvas.drawText("After canvas.restore()", 50, 250, paint);

// draw a thick dashed line
DashPathEffect dashPath =
                new DashPathEffect(new float[]{20,5}, 1);
//paint.setPathEffect(dashPath);*/
