using UnityEngine;
using System.Collections;

namespace com.deeperbeige.lib
{
    public class Colours
    {
        // Changes all child materials to the given colour
        public static void change(GameObject item, Color colour)
        {
            Component[] renderers = item.GetComponentsInChildren(typeof(Renderer));
            foreach (Renderer renderer in renderers)
            {
                renderer.material.color = colour;
            }
        }

        // Creates a native Color object from a hex ref that looks like any of the below
        //
        //   Colours.fromHex("RRGGBB");
        //   Colours.fromHex("0xRRGGBB");
        //   Colours.fromHex("#RRGGBB")
        //
        // Returns red on failure to parse
        public static Color fromHex(string hex)
        {
            if (hex.Length > 6)
            {
                if (hex.Substring(0, 2) == "0x") hex = hex.Substring(2);
                if (hex.Substring(0, 1) == "#")  hex = hex.Substring(1);
            }

            if (hex.Length != 6) return Color.red;

            string hexR = hex.Substring(0, 2);
            string hexG = hex.Substring(2, 2);
            string hexB = hex.Substring(4, 2);

            int decR = int.Parse(hexR, System.Globalization.NumberStyles.HexNumber);
            int decG = int.Parse(hexG, System.Globalization.NumberStyles.HexNumber);
            int decB = int.Parse(hexB, System.Globalization.NumberStyles.HexNumber);

            return fromRGB(decR, decG, decB);
        }

        // Creates a new native Color object from integer RGB values from 0 to 255
        public static Color fromRGB(int r, int g, int b)
        {
            return new Color((float)r / 255f, (float)g / 255, (float)b / 255);
        }
        
		// Creates a new native Color object from integer RGBA values from 0 to 255
		public static Color fromRGBA(int r, int g, int b, int a)
		{
			return new Color((float)r / 255f, (float)g / 255, (float)b / 255, (float)a / 255);
		}
	}
}