package tw.edu.hust.bn98111;

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, 7, 15, 8, Color.MAGENTA);
	private Block bb = new Block(40, 40, 80, 20, Color.BLUE);
	private Bar bar = new Bar(150, 410, 50, 80, 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);
		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;
	}

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