using System;
using System.Collections.Generic;
using System.Reflection;
using NBF.Setting;

namespace NBF
{
    public static class ListExtends
    {
        public static void SortBySortAttribute(this List<OptionBase> list)
        {
            if (list == null)
                throw new ArgumentNullException(nameof(list));

            list.Sort((a, b) =>
            {
                var orderA = GetSortOrder(a);
                var orderB = GetSortOrder(b);
                return orderA.CompareTo(orderB);
            });
        }

        private static int GetSortOrder(OptionBase option)
        {
            if (option == null)
                return 999;

            var sortAttribute = option.GetType()
                .GetCustomAttribute<SortAttribute>(inherit: false);

            return sortAttribute?.Sort ?? 999;
        }
    }
}