using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Text;

namespace InABox.Core
{
    public static class DFLayoutUtils
    {
        public static Color? ConvertObjectToColour(object? colour)
        {
            if (colour is string str)
            {
                if (str.StartsWith('#'))
                {
                    var trimmed = str.TrimStart('#');
                    try
                    {
                        if (trimmed.Length == 6)
                        {
                            return Color.FromArgb(
                                Int32.Parse(trimmed[..2], NumberStyles.HexNumber),
                                Int32.Parse(trimmed.Substring(2, 2), NumberStyles.HexNumber),
                                Int32.Parse(trimmed.Substring(4, 2), NumberStyles.HexNumber));
                        }
                        else if (trimmed.Length == 8)
                        {
                            return Color.FromArgb(Int32.Parse(trimmed, NumberStyles.HexNumber));
                        }
                        else
                        {
                            return null;
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Send(LogType.Error, "", $"Error parsing colour '{str}': {e.Message}");
                        return null;
                    }
                }
                else if (Enum.TryParse<KnownColor>(str, out var result))
                {
                    return Color.FromKnownColor(result);
                }
                return null;
            }
            return null;
        }

    }
}
