//import java.awt.Point;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;


/**
 * this is a tool the paints all similarity colored pixels to the new selected color
 *
 * @author Ian Roberts.
 *         Created Mar 25, 2008.
 */
public class PaintBucketTool extends Brush {
	private int w,h;
	/**
	 * this creates the paint bucket tool for use
	 *
	 */
	public PaintBucketTool(){
		super(20,new File("paint.bmp"),"paintbucket");
		
	}
	@Override
	public void Paint(Canvas c,int x,int y){
		BufferedImage buf = c.getImage();
		this.w=buf.getWidth();
		this.h=buf.getHeight();
		Color col = new Color(c.getImage().getRGB(x,y));
		paintbucket(x,y,c,true,col.getRed(),col.getBlue(),col.getGreen(),c.getPaint().tolerance.getValue());
		c.repaint();
	}
	private void paintbucket(int x, int y, Canvas c,boolean dir,int red, int blue,int green,int tol){
		boolean A=false,B=false,C=false,D=false;
		BufferedImage b = c.getImage();
		if(dir){
			if(!(x+1>=this.w)){
				Color t = new Color(b.getRGB(x+1,y));
				if(t.getRed()>=red-tol&&t.getRed()<=red+tol
					&&t.getBlue()>=blue-tol&&t.getBlue()<=blue+tol
					&&t.getGreen()>=green-tol&&t.getGreen()<=green+tol
					&&c.isSelected(x+1,y))
				{
					b.setRGB(x+1,y,c.getPaint().cc.getColor().getRGB());
					A=true;
				}
				
			}
			if(!(y-1<=0)){
				Color t = new Color(b.getRGB(x,y-1));
				if(t.getRed()>=red-tol&&t.getRed()<=red+tol
					&&t.getBlue()>=blue-tol&&t.getBlue()<=blue+tol
					&&t.getGreen()>=green-tol&&t.getGreen()<=green+tol
					&&c.isSelected(x,y-1))
				{
					b.setRGB(x,y-1,c.getPaint().cc.getColor().getRGB());
					B=true;
				}
				
			}
			if(!(x-1<=0)){
				Color t = new Color(b.getRGB(x-1,y));
			if(t.getRed()>=red-tol&&t.getRed()<=red+tol
					&&t.getBlue()>=blue-tol&&t.getBlue()<=blue+tol
					&&t.getGreen()>=green-tol&&t.getGreen()<=green+tol
					&&c.isSelected(x-1,y)){
				b.setRGB(x-1,y,c.getPaint().cc.getColor().getRGB());
				C=true;}
				
			}
			if(!(y+1>=this.h)){
				Color t = new Color(b.getRGB(x,y+1));
			if(t.getRed()>=red-tol&&t.getRed()<=red+tol
					&&t.getBlue()>=blue-tol&&t.getBlue()<=blue+tol
					&&t.getGreen()>=green-tol&&t.getGreen()<=green+tol
					&&c.isSelected(x,y+1))
				{
				b.setRGB(x,y+1,c.getPaint().cc.getColor().getRGB());
				D=true;
				}
				
			}
			if(A){paintbucket(x+1,y,c,true,red, blue, green, tol);}
			if(B){paintbucket(x,y-1,c,true,red, blue, green, tol);}
			if(C){paintbucket(x-1,y,c,true,red, blue, green, tol);}
			if(D){paintbucket(x,y+1,c,true,red, blue, green, tol);}
		}
	}

}
