using System;
using System.Text.RegularExpressions;
using System.Windows.Media;

namespace BS.Shared.Extensions
{
    public static class ColorExtensions
    {
        public static int GetPerceivedBrightness(this Color c)
        {
            return (int)Math.Sqrt(c.R * c.R * .241 + c.G * c.G * .691 + c.B * c.B * .068);
        }

		public static Color FromHexString(this Color c, string wert)
	    {
		    byte a = 255;
			byte r = 0;
			byte g = 0;
			byte b = 0;
			
		    if (wert.Contains("#"))
			    wert = wert.Remove(0,1);

		    var regex = new Regex(@"^#?[A-Fa-f0-9]{6,8}");
		    var gueltig = regex.IsMatch(wert);

			if (!gueltig) return Color.FromArgb(a, r, g, b);

			if(wert.Length == 8)
			{
				var AA = wert.Substring(0, 2);
				a = Convert.ToByte(AA, 16);
			}

			r = Convert.ToByte(wert.Length == 8 ? wert.Substring(2, 2) : wert.Substring(0, 2), 16);
			g = Convert.ToByte(wert.Length == 8 ? wert.Substring(4, 2) : wert.Substring(2, 2), 16);
			b = Convert.ToByte(wert.Length == 8 ? wert.Substring(6, 2) : wert.Substring(4, 2), 16);

		    return Color.FromArgb(a, r, g, b);
	    }
    }
}