package tw.edu.hust.bn98000;

import android.R.color;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

public class GameSurfaceView extends SurfaceView {
	private Ball b1 = new Ball(240, 350, 15, 7, 5, Color.RED);
//	private Ball b2 = new Ball(240, 350, 10, -20, -20, Color.GREEN);
//	private Ball b3 = new Ball(240, 350, 5, 10, 10, Color.BLUE);
	private Bar bar = new Bar( 150, 410, 80, 20, Color.CYAN);
	private Block block = new Block( 40, 80, 80, 20, Color.YELLOW);
	private Paint bgPen = new Paint();
	private int width=320;
	private int height=480;
    
	// ¥»¤å
	public GameSurfaceView(Context context) {
		super(context);

		// TODO Auto-generated constructor stub
		
	}

	public GameSurfaceView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public GameSurfaceView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	//

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		bgPen.setColor(color.white);
		bgPen.setAlpha(0xFF);
		canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), bgPen);
		b1.draw(canvas);
//		b2.draw(canvas);
//		b3.draw(canvas);
		bar.draw(canvas);
		block.draw(canvas);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		//int specWMode = MeasureSpec.getMode(widthMeasureSpec);
		//int specHMode = MeasureSpec.getMode(heightMeasureSpec);
		
		this.width = MeasureSpec.getSize(widthMeasureSpec);
		this.height = MeasureSpec.getSize(heightMeasureSpec);
		if (bar != null) bar.setSize( width, height);
		setMeasuredDimension( width, height);
	}
	

	int x1, y1;
	int x2, y2;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch ( event.getAction() ) {
          case MotionEvent.ACTION_DOWN: // touch down
      		x1 = (int) event.getX();
    		y1 = (int) event.getY();
        	break;
          case MotionEvent.ACTION_MOVE: // touch drag with the ball
        	x2 = (int) event.getX();
        	y2 = (int) event.getY();
        	bar.moveCenterToPos(x2);
    		this.invalidate();
        	break;
          case MotionEvent.ACTION_UP: 
        	x1 = x2 = (int) event.getX();
        	y1 = y2 = (int) event.getY();
        	break;
		}
		//
		return true;
	}

	public void moveBall(SurfaceHolder sHolder) {
		// TODO Auto-generated method stub
		b1.move(this.getWidth(), this.getHeight(), block, bar);
		Canvas cc = sHolder.lockCanvas();
		if (cc == null) return;
		onDraw(cc);
		sHolder.unlockCanvasAndPost(cc);
		
	}	
}
