using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace AMWD.Common.AspNetCore.Utilities
{
///
/// Provides helpers for webpages.
///
public static class HtmlHelper
{
///
/// Checks whether a color is considered as dark.
///
/// The color (hex or rgb - as defined in CSS)
/// true when the color is dark otherwise false.
public static bool IsDarkColor(string color)
{
if (string.IsNullOrWhiteSpace(color))
return false;
int r, g, b;
var rgbMatch = Regex.Match(color, @"^rgba?\(([0-9]+), ?([0-9]+), ?([0-9]+)");
var hexMatchFull = Regex.Match(color, @"^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$");
var hexMatchLite = Regex.Match(color, @"^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$");
if (rgbMatch.Success)
{
r = Convert.ToInt32(rgbMatch.Groups[1].Value);
g = Convert.ToInt32(rgbMatch.Groups[2].Value);
b = Convert.ToInt32(rgbMatch.Groups[3].Value);
}
else if (hexMatchFull.Success)
{
r = Convert.ToInt32(hexMatchFull.Groups[1].Value, 16);
g = Convert.ToInt32(hexMatchFull.Groups[2].Value, 16);
b = Convert.ToInt32(hexMatchFull.Groups[3].Value, 16);
}
else if (hexMatchLite.Success)
{
r = Convert.ToInt32(new string(hexMatchLite.Groups[1].Value.First(), 2), 16);
g = Convert.ToInt32(new string(hexMatchLite.Groups[2].Value.First(), 2), 16);
b = Convert.ToInt32(new string(hexMatchLite.Groups[3].Value.First(), 2), 16);
}
else
{
return false;
}
double luminance = (r * 0.299 + g * 0.587 + b * 0.114) / 255;
return luminance <= 0.5;
}
}
}