using System.Diagnostics.CodeAnalysis;
using PkmnLib.Static.Species;
using PkmnLib.Static.Utils;
namespace PkmnLib.Static.Libraries;
///
/// The library for all species in the game.
///
public interface IReadOnlySpeciesLibrary : IEnumerable
{
///
/// Tries to get a species from the library. Returns false if the species is not found.
///
bool TryGet(StringKey key, [MaybeNullWhen(false)] out ISpecies value);
///
/// Tried to get a species from the library by its national dex number. Returns false if the species is not found.
///
bool TryGetById(int id, [MaybeNullWhen(false)] out ISpecies value);
///
/// Gets a random species from the library.
///
ISpecies GetRandom(IRandom random);
///
/// The amount of species in the library.
///
int Count { get; }
///
/// Whether the library is empty.
///
bool IsEmpty { get; }
///
/// Finds the Pokémon that evolves into the given species. If the species does not evolve, returns null.
/// If multiple species evolve into the given species, returns the first one found.
///
ISpecies? FindPreEvolution(ISpecies species);
}
///
public class SpeciesLibrary : DataLibrary, IReadOnlySpeciesLibrary
{
private Dictionary _preEvolutionCache = new();
///
public bool TryGetById(int id, [MaybeNullWhen(false)] out ISpecies value)
{
return this.FirstOrDefault(s => s.Id == id) is { } species
? (value = species) != null
: (value = default) != null;
}
///
public ISpecies? FindPreEvolution(ISpecies species)
{
if (_preEvolutionCache.TryGetValue(species, out var preEvolution))
return preEvolution;
foreach (var s in this)
{
if (s.EvolutionData.All(e => e.ToSpecies != species.Name))
continue;
_preEvolutionCache[species] = s;
return s;
}
return null;
}
}