using UnityEngine;
using System.Collections;

public static class ColorExtensions 
{
	static public readonly Color transparentBlack = new Color(0f, 0f, 0f, 0f);
	
	static public string ToString2(this Color value)
	{
		return string.Format("({0:0.######}, {1:0.######}, {2:0.######}, {3:0.######})", value.r, value.g, value.b, value.a);
	}
	
	static public bool Approximately(this Color value, Color other)
	{
		return Mathf.Approximately(value.r, other.r) &&
			Mathf.Approximately(value.g, other.g) &&
			Mathf.Approximately(value.b, other.b) &&
			Mathf.Approximately(value.a, other.a);
	}
	
	static public bool TryParse(string toParse, out Color parsed)
	{
		parsed = default(Color);
		
		if(!toParse.StartsWith("(") || !toParse.EndsWith(")"))
		{
			return false;
		}
		var trimmedToken = toParse.Substring(1, toParse.Length - 2);
		
		var vectorComponentTokens = trimmedToken.Split(',');
		if(vectorComponentTokens.Length != 3 && vectorComponentTokens.Length != 4)
		{
			return false;
		}
		
		float r = 0f;
		float g = 0f;
		float b = 0f;
		float a = 1f;
		bool success = true;
		success &= float.TryParse(vectorComponentTokens[0], out r);
		success &= float.TryParse(vectorComponentTokens[1], out g);
		success &= float.TryParse(vectorComponentTokens[2], out b);
		if(vectorComponentTokens.Length > 3)
		{
			success &= float.TryParse(vectorComponentTokens[3], out a);
		}
		if(!success)
		{
			return false;
		}
		
		parsed = new Color(r, g, b, a);
		return true;
	}

	static public float GetHue(float r, float g, float b, float max, float d)
	{
		const float oneSixth = 1f / 6f;
		float h = 0;
		
		if(max == r)
		{
			h = (g - b) / d + ((g < b) ? 6f : 0f);
		}
		else if (max == g)
		{
			h = (b - r) / d + 2f;
		}
		else
		{
			h = (r - g) / d + 4f;
		}
		h *= oneSixth;
		
		return h;
	}
	
	static public string GetName(this Color value)
	{
		ColorHsv colorHsv = value;
		return colorHsv.GetName();
	}
	
	static public Color Complement(this Color value)
	{
		ColorHsv colorHsv = value;
		colorHsv.h = (colorHsv.h + 0.5f) % 1f;
		return colorHsv;
	}

	static public Color Darken(this Color value, float percentage)
	{
		ColorHsv colorHsv = value;
		colorHsv.v *= 1f - percentage;
		return colorHsv;
	}
}
