using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Data;
using System.Windows.Media;
using Aitex.Core.RT.Log;

namespace MECF.Framework.UI.Core.Converters;

public class StringToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string str)
        {
            const string pattern = @"^#([A-Fa-f0-9]{8})$";
            return Regex.IsMatch(str, pattern)
                ? ColorConverter.ConvertFromString(str) // convert string to color
                : Colors.Transparent; // miss match pattern
        }

        return Colors.Transparent; // not a string
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value is Color color)
            return $"#{color.A:X2}{color.R:X2}{color.G:X2}{color.B:X2}";
        else
            return "";
    }
}