package Begin;
import DreamBubbleMidlet;

import java.io.IOException;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class BeforeMenu extends Canvas implements Runnable {

	public DreamBubbleMidlet dreamBubbleMidlet;

	private Image srcImage;

	private int[] srcRgbImage;
	private int[] shadowRgbImage;

	private int imgWidth, imgHeight;
	private int screenWidth, screenHeight;
	
	private boolean isEnd;

	public BeforeMenu(DreamBubbleMidlet dreamBubbleMidlet) {
		this.dreamBubbleMidlet = dreamBubbleMidlet;
		this.setFullScreenMode(true);
		this.screenWidth = this.getWidth();
		this.screenHeight = this.getHeight();

		try {
			this.srcImage = Image.createImage("/Begin/2.png");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		this.imgWidth = srcImage.getWidth();
		this.imgHeight = srcImage.getHeight();

		this.srcRgbImage = new int[imgWidth * imgHeight];
		this.srcImage.getRGB(srcRgbImage, 0, imgWidth, 0, 0, imgWidth,
				imgHeight);
		this.shadowRgbImage = new int[srcRgbImage.length];

		System.arraycopy(srcRgbImage, 0, shadowRgbImage, 0,
				shadowRgbImage.length);

		for (int i = 0; i < shadowRgbImage.length; i++) {
			shadowRgbImage[i] &= 0x00ffffff;
		}
	}

	public void paint(Graphics g) {
		g.setColor(0, 0, 0);
		g.fillRect(0, 0, screenWidth, screenHeight);
		g.drawRGB(shadowRgbImage, 0, imgWidth, (screenWidth - imgWidth) / 2,
				(screenHeight - imgHeight) / 2, imgWidth, imgHeight, true);
	}

	public void run() {
		while (!isEnd) {
			boolean changed = false;
			int alpha = 0;
			int oldAlpha = 0;
			for (int i = 0; i < shadowRgbImage.length; i++) {
				// 获取渐变图片的某一像素的alpha值
				alpha = (shadowRgbImage[i] & 0xff000000) >>> 24;
				// 原始图片的对应像素的alpha值
				oldAlpha = (srcRgbImage[i] & 0xff000000) >>> 24;
				if (alpha + 8 < oldAlpha) {
					shadowRgbImage[i] = ((alpha + 8) << 24)
							| (shadowRgbImage[i] & 0x00ffffff);
					changed = true;
				}
			}
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			repaint();
			// 当所有像素的alpha值都达到原始值后,线程运行结束
			if (!changed) {
				break;
			}
		}
		showNextScreen();
	}

	public void showMe() {
		new Thread(this).start();
		this.dreamBubbleMidlet.show(this);
	}

	public void showNextScreen() {
		this.isEnd = true;
		this.dreamBubbleMidlet.menu.showMe();
	}
}
