using System.Collections.Generic;
using System.Linq;

using UnityEngine;

using UPG.Extensions;

namespace BR.BattleRoyale.Items
{
    [CreateAssetMenu(fileName = "New Drop Table", menuName = "Scriptables/Drop Table")]
    public class DropTable : ScriptableObject
    {
        #region STATIC METHODS
        public static DropTable GetTableByName(string _name) =>
            Resources.Load<DropTable>("Scriptables/Drop Table/" + _name);
        #endregion

        #region PUBLIC FIELDS
        public List<GameObject> Wands = new List<GameObject>();
        public List<GameObject> Potions = new List<GameObject>();
        #endregion

        #region DATA BY RARITY METHODS
        public int NumberOfWandsWithRarity(Rarity _rarity) =>
            Wands.Count(x => x.TryGetComponent(out Wand _wand) && _wand.Rarity == _rarity);
        public int NumberOfPotionsWithRarity(Rarity _rarity) =>
            Potions.Count(x => x.TryGetComponent(out Potion _potion) && _potion.Rarity == _rarity);
        public int NumberOfDropsWithRarity(Rarity _rarity) =>
            NumberOfWandsWithRarity(_rarity) + NumberOfPotionsWithRarity(_rarity);

        public GameObject GetRandomDropByRarity(Rarity _rarity)
        {
            List<GameObject> _objectsOfRarity = new List<GameObject>();

            while (_rarity != Rarity.Basic && NumberOfDropsWithRarity(_rarity) == 0)
                _rarity = (Rarity)((int)_rarity - 1);

            _objectsOfRarity.AddRange(Wands.FindAll(x => x != null && x.GetComponent<Wand>().Rarity == _rarity));
            _objectsOfRarity.AddRange(Potions.FindAll(x => x != null && x.GetComponent<Potion>().Rarity == _rarity));

            if (_objectsOfRarity.Count == 0)
                return null;

            return _objectsOfRarity.ToArray().RandomOrNull();
        }
        #endregion

        #region RESET METHODS
        public void SetDefault()
        {
            Wands = Resources.LoadAll<GameObject>("Prefabs/Wands").Distinct().ToList();

            Potions = Resources.LoadAll<GameObject>("Prefabs/Potions").Distinct().ToList();
        }
        #endregion
    }
}
