PkmnLib.NET/PkmnLib.Dynamic/ScriptHandling/ScriptIterator.cs

71 lines
1.7 KiB
C#

using System.Collections;
namespace PkmnLib.Dynamic.ScriptHandling;
public class ScriptIterator : IEnumerable<ScriptContainer>
{
private readonly IReadOnlyList<IEnumerable<ScriptContainer>> _scripts;
private int _index = -1;
private int _setIndex = -1;
public ScriptIterator(IReadOnlyList<IEnumerable<ScriptContainer>> scripts)
{
_scripts = scripts;
}
bool IncrementToNext()
{
if (_index != -1)
{
var current = _scripts[_index];
if (current is IScriptSet)
{
_setIndex += 1;
if (_setIndex >= current.Count())
{
_setIndex = -1;
}
else
{
return true;
}
}
}
_index += 1;
for (; _index < _scripts.Count; _index++)
{
switch (_scripts[_index])
{
case IScriptSet:
_setIndex = 0;
return true;
case ScriptContainer { IsEmpty: false }:
return true;
}
}
return false;
}
/// <inheritdoc />
public IEnumerator<ScriptContainer> GetEnumerator()
{
while (IncrementToNext())
{
var current = _scripts[_index];
yield return current switch
{
IScriptSet set => set.At(_setIndex),
ScriptContainer container => container,
_ => throw new InvalidOperationException("Invalid script type")
};
}
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}