import com.cult3d.*;
import com.cult3d.world.*;

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

public class Fading extends Thread implements Cult3DScript
{
	private final static int SLEEPTIME = 200;

	private boolean going = true;
	private boolean fading = false;
	private Color[] object_color;
	private int current_color = 0;
	private Texture object_texture;
	private Image object_image;
	private Graphics object_graphic;

	public Fading()
	{
		start();
	}

	public void run()
	{
		object_color = new Color[7];
		object_color[0] = new Color(23,32,63);
		object_color[1] = new Color(229,229,229);
		object_color[2] = new Color(212,185,96);
		object_color[3] = new Color(74,74,74);
		object_color[4] = new Color(128,19,24);
		object_color[5] = new Color(131,165,190);
		object_color[6] = new Color(174,174,174);

		object_texture = new Texture("bluecolor");
		object_image = Cult.createImage(object_texture.getWidth(),object_texture.getHeight());
		object_graphic = object_image.getGraphics();
		object_graphic.setColor(object_color[0]);

		while (going)
		{
			if (fading == true)
			{
				fadingColor();
			}
			try
			{
				sleep(SLEEPTIME);
			}
			catch (InterruptedException e){}
		}
	}

	public void switchColor(String arg)
	{
		if (fading == false)
		{
			current_color++;
			if (current_color >= object_color.length)
			{
				current_color = 0;
			}
			fading = true;
		}
	}

	public void fadingColor() {
		Color c_color = object_graphic.getColor();
		Color n_color = new Color(object_color[current_color].getRed(),object_color[current_color].getGreen(),object_color[current_color].getBlue());

		float or,og,ob,nr,ng,nb,incr,incg,incb;

		or = (float)c_color.getRed();
		og = (float)c_color.getGreen();
		ob = (float)c_color.getBlue();
		nr = (float)n_color.getRed();
		ng = (float)n_color.getGreen();
		nb = (float)n_color.getBlue();

		int cc = 30;
		incr = (nr-or)/((float)cc);
		incg = (ng-og)/((float)cc);
		incb = (nb-ob)/((float)cc);

		for (int i=0; i<cc; i++)
		{
			Color temp_c = new Color((int)(c_color.getRed()+i*incr),(int)(c_color.getGreen()+i*incg),(int)(c_color.getBlue()+i*incb));
			object_graphic.setColor(temp_c);
			object_graphic.fillRect(0,0,object_texture.getWidth(),object_texture.getHeight());
			object_texture.setTexture(object_image);

			try
			{
				sleep(20);
			}
			catch (InterruptedException e)
			{
				System.out.println("Sleep Error");
			}
		}

		object_graphic.setColor(object_color[current_color]);
		object_graphic.fillRect(0,0,object_texture.getWidth(),object_texture.getHeight());
		object_texture.setTexture(object_image);

		fading = false;
	}

	public void cult3dDestroy()
	{
		going = false;
	}
}
