package tw.edu.hust.bn98107;

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.View;

public class GameView extends View {
	private Ball b1 = new Ball(100, 350, 15, 7, 5, Color.RED);
	private Block bb= new Block(40,40, 80, 20, Color.BLUE);
	private Bar bar= new Bar(150,410, 80, 20, Color.DKGRAY);
	private Paint bgPen = new Paint();
	private int width=320;
	private int height=480;

	// ¥»¤å
	public GameView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		new Thread() {
			public void run() {
				// TODO Auto-generated method stub
				while (true) {
					b1.move(height,width,bb,bar);
					GameView.this.postInvalidate();
					try {
						sleep(30);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

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

	public GameView(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);
		canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), bgPen);
		b1.draw(canvas);
		bb.draw(canvas);
		bar.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);
		//
		setMeasuredDimension( width, height);
	}
	private boolean drag;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch (event.getAction()){
		case MotionEvent.ACTION_DOWN:
			int x=(int)event.getX();
			int y=(int)event.getY();
			if(bar.getRect().contains(x,y))
				drag =true;
			else
				drag=false;
			break;
		case MotionEvent.ACTION_MOVE:
			if (drag){
				int nx =(int)event.getX();
				bar.moveCenterToPos(nx);
			}
			break;
		case MotionEvent.ACTION_UP:
			break;
		}
		return true;
	}
	
}
