package com.one.vector;

import com.one.ImageProcessor;
import java.io.*;

public class GradientReplace extends Effect
{
	protected int startcolorA, startcolorB;
	protected int endcolorA, endcolorB;
	protected int startdistance, maxdelta;
	
	public GradientReplace()
	{
	}
	
	public void read(DataInputStream dis) throws IOException
	{
		name = dis.readUTF();
		hidden = dis.readBoolean();
		
		startcolorA = dis.readInt();
		startcolorB = dis.readInt();
		
		endcolorA = dis.readInt();
		endcolorB = dis.readInt();
		
		maxdelta = dis.readShort();
		
		startdistance = ImageProcessor.colorDistance(startcolorA, startcolorB);
	}
	
	public void write(DataOutputStream dos) throws IOException
	{
		dos.writeUTF(name);
		dos.writeBoolean(hidden);
		
		dos.writeInt(startcolorA);
		dos.writeInt(startcolorB);
		
		dos.writeInt(endcolorA);
		dos.writeInt(endcolorB);
		
		dos.writeShort(maxdelta);
	}
	
	public void apply(int[] rgb, int[] temp, int width, int height)
	{
		if(hidden)
		{
			return;
		}
		
		int aa = (endcolorA >> 24) & 0xFF;
		int ar = (endcolorA >> 16) & 0xFF;
		int ag = (endcolorA >> 8) & 0xFF;
		int ab = endcolorA & 0xFF;
		
		int ba = (endcolorB >> 24) & 0xFF;
		int br = (endcolorB >> 16) & 0xFF;
		int bg = (endcolorB >> 8) & 0xFF;
		int bb = endcolorB & 0xFF;
		
		int ra, rr, rg, rb;
		int distanceA, distanceB;
		int totaldistance;
		
		for(int i = 0; i < rgb.length; i++)
		{
			distanceA = ImageProcessor.colorDistance(rgb[i], startcolorA);
			distanceB = ImageProcessor.colorDistance(rgb[i], startcolorB);
			totaldistance = distanceA + distanceB;
			
			if(maxdelta < 0 || totaldistance - startdistance <= maxdelta)
			{
				ra = (aa * distanceB + ba * distanceA) / totaldistance;
				rr = (ar * distanceB + br * distanceA) / totaldistance;
				rg = (ag * distanceB + bg * distanceA) / totaldistance;
				rb = (ab * distanceB + bb * distanceA) / totaldistance;
				
				rgb[i] = (ra << 24) | (rr << 16) | (rg << 8) | rb;
			}
		}
	}
	
	public void setStartColors(int colorA, int colorB)
	{
		startcolorA = colorA;
		startcolorB = colorB;
		
		startdistance = ImageProcessor.colorDistance(startcolorA, startcolorB);
	}
	
	public void setEndColors(int colorA, int colorB)
	{
		endcolorA = colorA;
		endcolorB = colorB;
	}
	
	public void setMaxDelta(int value)
	{
		maxdelta = value;
	}
	
	public int getStartColorA()
	{
		return startcolorA;
	}
	
	public int getStartColorB()
	{
		return startcolorB;
	}
	
	public int getEndColorA()
	{
		return endcolorA;
	}
	
	public int getEndColorB()
	{
		return endcolorB;
	}
	
	public int getMaxDelta()
	{
		return maxdelta;
	}
}