using System;
using System.Collections.Generic;

namespace EonaCat.Logger.Helpers
{
    // This file is part of the EonaCat project(s) which is released under the Apache License.
    // See the LICENSE file or go to https://EonaCat.com/License for full license details.

    internal static class EnumHelper<T>
        where T : struct
    {
        static EnumHelper()
        {
            string[] names = Enum.GetNames(typeof(T));
            T[] values = (T[])Enum.GetValues(typeof(T));

            Names = new Dictionary<T, string>(names.Length);
            Values = new Dictionary<string, T>(names.Length * 2);

            for (int i = 0; i < names.Length; i++)
            {
                Names[values[i]] = names[i];
                Values[names[i]] = values[i];
                Values[names[i].ToLower()] = values[i];
            }
        }

        public static Dictionary<T, string> Names { get; }

        public static Dictionary<string, T> Values { get; }

        public static string ToString(T value)
        {
            return Names.TryGetValue(value, out string result) ? result : Convert.ToInt64(value).ToString();
        }

        public static bool TryParse(string input, bool ignoreCase, out T value)
        {
            if (string.IsNullOrEmpty(input))
            {
                value = default;
                return false;
            }

            return Values.TryGetValue(ignoreCase ? input.ToLower() : input, out value);
        }

        internal static T Parse(string input, bool ignoreCase, T defaultValue)
        {
            return TryParse(input, ignoreCase, out T result) ? result : defaultValue;
        }
    }
}