using System;

namespace Quadarax.Foundation.Core.Value
{
    public static class ValueConverter
    {

        public static object? ConvertTo(Type toType, string value)
        {
            if (string.IsNullOrEmpty(value)) return null;


            if (toType == typeof(string)) return (object)value;
            if (toType == typeof(int)) return (object)int.Parse(value);
            if (toType == typeof(long)) return (object)long.Parse(value);
            if (toType == typeof(bool)) return (object)bool.Parse(value);
            if (toType == typeof(double)) return (object)double.Parse(value);
            if (toType == typeof(float)) return (object)float.Parse(value);
            if (toType == typeof(decimal)) return (object)decimal.Parse(value);
            if (toType == typeof(byte)) return (object)byte.Parse(value);
            if (toType == typeof(sbyte)) return (object)sbyte.Parse(value);
            if (toType == typeof(short)) return (object)short.Parse(value);
            if (toType == typeof(ushort)) return (object)ushort.Parse(value);
            if (toType == typeof(uint)) return (object)uint.Parse(value);
            if (toType == typeof(ulong)) return (object)ulong.Parse(value);
            if (toType == typeof(char)) return (object)char.Parse(value);
            if (toType == typeof(Guid)) return (object)Guid.Parse(value);
            if (toType == typeof(TimeSpan)) return (object)TimeSpan.Parse(value);
            if (toType.IsEnum) return (object)Enum.Parse(toType, value, true);
            
            throw new NotSupportedException($"Cannot convert value to type '{toType}'. Not supported!");
        }

        public static TValue? ConvertTo<TValue>(string value)
        {
            return (TValue?)ConvertTo(typeof(TValue), value);
        }
    }
}
