package com.example.hello.android.bitmap_drawing_and_save;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 *
 * @author sawai
 */
public class CanvasView extends View
{

	private static final String LOG_TAG = "XXX";
	private Bitmap bitmap;
	private Canvas bitmapCanvas;
	private Paint bgPaint;
	private Paint fgPaint;

	public CanvasView(Context context)
	{
		super(context);
		Log.d("CanvasView", "new CanvasView()");
		bgPaint = new Paint();
		bgPaint.setColor(Color.BLACK);
		fgPaint = new Paint();
		fgPaint.setColor(Color.WHITE);
		fgPaint.setAntiAlias(true);
		setFocusable(false);
		setFocusableInTouchMode(false);
		setClickable(true);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh)
	{
		super.onSizeChanged(w, h, oldw, oldh);
		this.bitmap = null;
		this.bitmapCanvas = null;
	}

	public Bitmap getBitmap()
	{
		if (this.bitmap == null)
		{
			bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
		}
		return bitmap;
	}

	public Canvas getBitmapCanvas()
	{
		if (this.bitmapCanvas == null)
		{
			bitmapCanvas = new Canvas(getBitmap());
			bitmapCanvas.drawARGB(0, 0, 0, 0);
		}
		return bitmapCanvas;
	}

	@Override
	protected void onDraw(Canvas canvas)
	{
		super.onDraw(canvas);
		Log.d(LOG_TAG, "BitmapView#onDraw()");
		Log.d(LOG_TAG, String.format("Canvas size : (%d, %d)", canvas.getWidth(), canvas.getHeight()));

		int w = canvas.getWidth();
		int h = canvas.getHeight();

		// clear canvas
		canvas.drawRect(0, 0, w, h, bgPaint);

		// draw bitmap
		Bitmap bmp = getBitmap();
		int bmpW = bmp.getWidth();
		int bmpH = bmp.getHeight();
		Rect srcRect = new Rect(0, 0, bmpW, bmpH);
		Rect dstRect = new Rect(0, 0, bmpW, bmpH);
		canvas.drawBitmap(bmp, srcRect, dstRect, fgPaint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		Log.d(LOG_TAG, String.format("MotionEvent : action => %d (%f, %f)",
			event.getAction(), event.getX(), event.getY()));
		Canvas c = getBitmapCanvas();
		c.drawCircle(event.getX(), event.getY(), 10, fgPaint);
		invalidate();

		return true;
	}
}
