using System.Runtime.CompilerServices;

namespace PkmnLib.Dynamic.ScriptHandling;

/// <summary>
/// Helper functions for script execution.
/// </summary>
public static class ScriptExecution
{
    /// <summary>
    /// Executes a hook on all scripts in a source.
    /// </summary>
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void RunScriptHook(this IScriptSource source, Action<Script> hook)
    {
        var iterator = source.GetScripts();
        foreach (var container in iterator)
        {
            if (container.IsEmpty)
                continue;
            var script = container.Script;
            if (script.IsSuppressed)
                continue;
            hook(script);
        }
    }

    /// <summary>
    /// Executes a hook on all scripts in a list of sources. Note that this does not walk through the parents of the
    /// sources, but only the sources themselves.
    /// </summary>
    public static void RunScriptHook(this IReadOnlyList<IEnumerable<ScriptContainer>> source, Action<Script> hook)
    {
        foreach (var container in source.SelectMany(x => x))
        {
            if (container.IsEmpty)
                continue;
            var script = container.Script;
            if (script.IsSuppressed)
                continue;
            hook(script);
        }
    }

}