import java.awt.Graphics;
import java.awt.Color;

public class BoomBlock extends Block{
//Overview: A BoomBlock is destroyable Block
//	if a UserTank move close to it, it will explode;
	private int count;

	public BoomBlock(){
		super(true,1);
		count = 0;
	}
	public void explode(){
	//Modifies: this
	//Effects: decreaseHP the SimObject adjacent to this by 1
	//	and then destroy itself 
		synchronized(getGrid()){

		int newx, newy;
		for(int i=-1;i<=1;i++){
			for(int j=-1;j<=1;j++){
				newx=getX()+i;
				newy=getY()+j;
				if(getGrid().validLocation(newx,newy)){
					if (!getGrid().isSquareEmpty(newx, newy)) {
						SimObject so = getGrid().getObjectAt(newx,newy);
						if(so instanceof SimObject){
							so.decreaseHP(1);
						}
					}
				}
			}
		}
		
		}
	}
	public void drawImage(Graphics g, int x, int y, int w, int h){
		switch(count){
			case 0:
				g.setColor(getColor());
				g.fillRect(x,y,w-1,h-1);
				break;
			case 1:
				g.setColor(new Color(210,50,50));
				g.fillRect(x,y,w-1,h-1);
				break;
			case 2:
				g.setColor(Color.red);
				g.fillRect(x,y,w-1,h-1);
				break;
			case 3:
				drawExplosion(g,x,y,w,h);
				break;
		}
	}
	public void drawExplosion(Graphics g, int x, int y, int w, int h){
		int newx=0, newy =0;
		for(int i=-1;i<=1;i++){
			for(int j=-1;j<=1;j++){
				newx=getX()+i;
				newy=getY()+j;
				if(getGrid().validLocation(newx,newy)){
					g.setColor(Color.red);
					g.drawOval(x+i*w-1,y+j*h-1,w-3,h-3);
				}
			}
		}
	}
	synchronized public void die(){
		if(count<3){
			count=3;
			delay(200);
		}else{
			super.die();
		}
	}
	
	public void executeTurn() throws RuntimeException{
		super.executeTurn();
		delay(300);
		synchronized(getGrid()){
			int newx, newy;
			if(count==0){	
				for(int row=-1;row<=1;row++){
					for(int col=-1;col<=1;col++){
						newx=getX()+col;
						newy=getY()+row;
						if (getGrid().validLocation(newx, newy)) {
							if (!getGrid().isSquareEmpty(newx, newy)) {
								SimObject so = getGrid().getObjectAt(newx,newy);
								if(so instanceof UserTank){
									count=1;
								}
							}
						}
					}
				}
			}else if(count<3){
				count++;
				//delay(300);
			}else{
				explode();
			}
		}
	}
}