package com.one.vector;

import java.util.EmptyStackException;
import java.io.*;
import com.one.*;

public class AreaFill extends Effect
{
	protected int color;
	protected double x, y;
	
	protected IntStack xps, yps;
	
	public AreaFill()
	{
		xps = new IntStack();
		yps = new IntStack();
	}
	
	public void read(DataInputStream dis) throws IOException
	{
		name = dis.readUTF();
		hidden = dis.readBoolean();
		
		color = dis.readInt();
		
		x = dis.readFloat();
		y = dis.readFloat();
	}
	
	public void write(DataOutputStream dos) throws IOException
	{
		dos.writeUTF(name);
		dos.writeBoolean(hidden);
		
		dos.writeInt(color);
		
		dos.writeFloat((float)x);
		dos.writeFloat((float)y);
	}
	
	public void apply(int rgb[], int[] temp, int width, int height)
	{
		if(hidden)
		{
			return;
		}
		
		int cx = (int)((double)width * x);
		int cy = (int)((double)height * y);
		
		if(cx < 0 || cx >= width || cy < 0 || cy >= height)
		{
			return;
		}
		
		xps.clear();
		yps.clear();
		
		xps.push(cx);
		yps.push(cy);
		
		int interior;
		int index;
		
		index = cx + cy * width;
		interior = rgb[index];
		rgb[index] = color;
		
		try
		{
			while(true)
			{
				try
				{
					cx = xps.pop();
					cy = yps.pop();
					
					if(cx - 1 >= 0)
					{
						index = (cx - 1) + cy * width;
						
						if(rgb[index] == interior)
						{
							xps.push(cx - 1);
							yps.push(cy);
							
							rgb[index] = color;
						}
					}
					
					if(cx + 1 < width)
					{
						index = (cx + 1) + cy * width;
						
						if(rgb[index] == interior)
						{
							xps.push(cx + 1);
							yps.push(cy);
							
							rgb[index] = color;
						}
					}
					
					if(cy - 1 >= 0)
					{
						index = cx + (cy - 1) * width;
						
						if(rgb[index] == interior)
						{
							xps.push(cx);
							yps.push(cy - 1);
							
							rgb[index] = color;
						}
					}
					
					if(cy + 1 < height)
					{
						index = cx + (cy + 1) * width;
						
						if(rgb[index] == interior)
						{
							xps.push(cx);
							yps.push(cy + 1);
							
							rgb[index] = color;
						}
					}
				}
				catch(StackOverflowException soe)
				{
					xps.clear();
					yps.clear();
					
					xps.push(cx);
					yps.push(cy);
				}
			}
		}
		catch(EmptyStackException ese)
		{
		}
	}
	
	public void setColor(int color)
	{
		this.color = color;
	}
	
	public void setPosition(double x, double y)
	{
		this.x = x;
		this.y = y;
	}
	
	public int getColor()
	{
		return color;
	}
	
	public double getX()
	{
		return x;
	}
	
	public double getY()
	{
		return y;
	}
}