package jp.sourceforge.nicoro;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class AsyncBitmapDrawable extends Drawable
		implements Handler.Callback {
	private Bitmap mBitmap;
	private Paint mPaint = new Paint();
	private final Rect mDstRect = new Rect();
	private Handler mHandler;
	private int mWidth;
	private int mHeight;
	private boolean mScale;

	public AsyncBitmapDrawable(int width, int height) {
	    this(width, height, false);
	}
    public AsyncBitmapDrawable(int width, int height, boolean scale) {
		mWidth = width;
		mHeight = height;
		mHandler = new Handler(this);
		mScale = scale;
	}
    public AsyncBitmapDrawable(Bitmap bitmap, int width, int height) {
        this(bitmap, width, height, false);
    }
    public AsyncBitmapDrawable(Bitmap bitmap, int width, int height, boolean scale) {
		mBitmap = bitmap;
		mWidth = width;
		mHeight = height;
		mScale = scale;
	}

	public Message obtainMessage() {
		return mHandler.obtainMessage();
	}

	public Handler getHandler() {
	    return mHandler;
	}

	// Drawable

	@Override
	public void draw(Canvas canvas) {
		copyBounds(mDstRect);
		if (mBitmap == null) {
			// TODO 色適当
//			mDstRect.set(0, 0, 0, 0);
			mPaint.setColor(0xff808080);
			canvas.drawRect(mDstRect, mPaint);
		} else {
		    if (mScale) {
	            mPaint.setFilterBitmap(true);
		    } else {
    			int diffWidth = (mDstRect.width() - mBitmap.getWidth()) / 2;
    			int diffHeight = (mDstRect.height() - mBitmap.getHeight()) / 2;
    			mDstRect.left += diffWidth;
    			mDstRect.right -= diffWidth;
    			mDstRect.top += diffHeight;
    			mDstRect.bottom -= diffHeight;
		    }
			canvas.drawBitmap(mBitmap, null, mDstRect, mPaint);
		}
	}

    @Override
    public int getIntrinsicWidth() {
    	return mWidth;
    }

    @Override
    public int getIntrinsicHeight() {
    	return mHeight;
    }

	@Override
	public int getOpacity() {
		// TODO 常にこれだとちょっとコスト高い？
		return PixelFormat.TRANSLUCENT;
	}

	@Override
	public void setAlpha(int alpha) {
		mPaint.setAlpha(alpha);
	}

	@Override
	public void setColorFilter(ColorFilter cf) {
		mPaint.setColorFilter(cf);
	}

	// implements Handler.Callback

	@Override
	public boolean handleMessage(Message msg) {
		mBitmap = (Bitmap) msg.obj;
		invalidateSelf();
		return true;
	}

}
