using System;

namespace Plane
{
    public static class MathExtensions
    {
        public static bool IsInRange<T>(this T value, T min, T max) where T : struct, IComparable<T>
        {
            if (min.CompareTo(max) > 0)
            {
                throw new ArgumentException($"The {nameof(min)} argument ({min}) must be less than or equal to the {nameof(max)} argument ({max}).");
            }
            return value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0;
        }

        public static T Limit<T>(this T value, T? min = null, T? max = null) where T : struct, IComparable<T>
        {
            if (min.HasValue && max.HasValue && min.Value.CompareTo(max.Value) > 0)
            {
                throw new ArgumentException($"The {nameof(min)} argument ({min}) must be less than or equal to the {nameof(max)} argument ({max}).");
            }
            if (!min.HasValue && !max.HasValue)
            {
                throw new ArgumentException($"The {nameof(min)} argument and the {nameof(max)} argument are both missing.");
            }
            if (min.HasValue && value.CompareTo(min.Value) < 0) return min.Value;
            if (max.HasValue && value.CompareTo(max.Value) > 0) return max.Value;
            return value;
        }
    }
}
