package retrobox.themes;

import java.util.HashMap;
import java.util.Map;

import xtvapps.core.Utils;

public class Color {
	private static final String LOGTAG = Color.class.getSimpleName();
	private static Map<String, Color> namedColors = new HashMap<String, Color>();
	
	public int r;
	public int g;
	public int b;
	public int a;

	public static void clearNamedColors() {
		namedColors.clear();
	}

	public static void addNamedColor(String name, String spec) {
		if (name == null || spec == null) {
			throw new RuntimeException("Invalid named color name:" + name + ", spec:" + spec);
		}
		Color color = build(spec);
		if (color!=null) namedColors.put(name, color);
	}
	
	public static Color getNamedColor(String name) {
		Color color = namedColors.get(name);
		if (color == null) {
			throw new RuntimeException("Unknown color:" + name );
		}
		return color;
	}
	
	public static Color build(String spec, Color defaultColor) {
		if (spec == null) return defaultColor;
		return build(spec);
	}
	
	public static Color build(String spec) {
		if (spec != null) {
			
			Color namedColor = namedColors.get(spec);
			if (namedColor!=null) {
				return clone(namedColor);
			}
			
			if (spec.startsWith("#") && spec.length()==9) {
				spec = spec.substring(1);
				
				Color color = new Color();
				color.a = buildComponent(spec.substring(0, 2));
				color.r = buildComponent(spec.substring(2, 4));
				color.g = buildComponent(spec.substring(4, 6));
				color.b = buildComponent(spec.substring(6, 8));
				return color;
			} else {
				throw new RuntimeException("Unknown color:" + spec);
			}
		}

		return null;
	}

	private static int buildComponent(String hex) {
		return Utils.strHex2i(hex, 0);
	}

	public int asInt() {
		return a << 24 | r << 16 | g << 8 | b;
	}

	public String asHex() {
		return String.format("#%02x%02x%02x%02x", a, r, g, b);
	}
	
	private static Color clone(Color color) {
		Color newColor = new Color();
		newColor.a = color.a;
		newColor.r = color.r;
		newColor.g = color.g;
		newColor.b = color.b;
		return newColor;
	}

}

@@ -62,19 +62,67 @@
 va.util.
-Map
+HashSet;%0Aimport java.util.Map;%0Aimport java.util.Set
 ;%0A%0Aimpor
@@ -232,16 +232,70 @@
 Name();%0A
+%09private static final String PRIOR_PREFIX = %22prior_%22;%0A
 %09private
@@ -365,16 +365,81 @@
 lor%3E();%0A
+%09private static Set%3CString%3E priorColors = new HashSet%3CString%3E();%0A
 %09%0A%09publi
@@ -557,16 +557,39 @@
 lear();%0A
+%09%09priorColors.clear();%0A
 %09%7D%0A%0A%09pub
@@ -770,20 +770,189 @@
  spec);%0A
-
 %09%09%7D%0A
+%09%09%0A%09%09if (priorColors.contains(name)) return;%0A%09%09%0A%09%09if (name.startsWith(PRIOR_PREFIX)) %7B%0A%09%09%09name = name.substring(PRIOR_PREFIX.length());%0A%09%09%09priorColors.add(name);%0A%09%09%7D%0A%09%09%0A
 %09%09Color 

Allow to override color priority