import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;


/**
 * TODO Put here a description of what this class does.
 *
 * @author Ian Roberts.
 *         Created Apr 11, 2008.
 */
public class MoverTool extends Tool {
	/**
	 * 
	 * Makes a new Tool capable of moving selected pixels around.
	 *
	 */
	 BufferedImage img;
	private int w=-1,h=-1;
	/**
	 * 
	 * Creates a new movertool using the hardcoded resource move.bmp
	 *
	 */
	public MoverTool(){
		super(20,new File("move.bmp"),"Move Selected");
	}
	@Override
	public void Paint(Canvas c, int x, int y){
		this.c=c;
		if(this.w==-1&&this.h==-1){
			int W=-1;
			int H=-1;
			int MW=-1;
			int MH=-1;
			for(int i=0;i<this.c.getImage().getWidth();i++){
				for(int j=0;j<this.c.getImage().getWidth();j++){
					if(W==-1&&c.isSelected(i,j)){
						W=i;
					}
					if(H==-1&&c.isSelected(i,j)){
						H=j;
					}
					if(c.isSelected(i,j)&&i<W){
						W=i;
					}
					if(c.isSelected(i,j)&&j<H){
						H=j;
					}
					if(c.isSelected(i,j)&&i>MW){
						MW=i;
					}
					if(c.isSelected(i,j)&&j>MH){
						MH=j;
					}
				}
			}
			this.w=Math.abs(MW-W)+1;
			this.h=Math.abs(MH-H)+1;
			this.img = new BufferedImage(this.w,this.h,TYPE_INT_ARGB);
			for(int i=0;i<this.w;i++){
				for(int j=0;j<this.h;j++){
					if(c.isSelected(i+W,j+H)){
						this.img.setRGB(i,j,c.getImage().getRGB(i+W,j+H));
					}
				}
			}
			for(int i=0;i<this.w;i++){
				for(int j=0;j<this.h;j++){
					if(c.isSelected(i+W,j+H)){
						c.getImage().setRGB(i+W,j+H,Color.white.getRGB());
					}
				}
			}
		}
		
		this.x=x-this.w/2;
		this.y=y-this.h/2;
		c.repaint();
	}
	@Override
	public void finish() {
		Graphics2D g = (Graphics2D)this.c.getImage().getGraphics();
		g.drawImage(this.img,null,this.x,this.y);
		this.img=null;
		this.w=-1;
		this.h=-1;
		this.c.repaint();
	}

}
