using System;
using System.Collections.Generic;
using System.Linq;
using SGModule.Common.Interface;

namespace SGModule.Common.Helper {
    public static class RandomHelper {
        private static readonly Random _random = new();

        public static T RandomByWeight<T>(IList<T> items, T fallback) where T : class, IWeighted {
            var totalWeight = items.Sum(item => item.Weight);
            if (totalWeight <= 0) {
                return fallback;
            }

            var roll = _random.Next(0, totalWeight);
            var cumulative = 0;

            foreach (var item in items) {
                cumulative += item.Weight;
                if (roll < cumulative) {
                    return item;
                }
            }

            return items.Last();
        }
    }
}
