using System;
using System.Collections.Generic;
using System.Linq;
using StardewModdingAPI.Events;
using StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands;
namespace StardewModdingAPI.Mods.ConsoleCommands
{
/// The main entry point for the mod.
public class ModEntry : Mod
{
/*********
** Fields
*********/
/// The commands to handle.
private IConsoleCommand[] Commands;
/// The commands which may need to handle update ticks.
private IConsoleCommand[] UpdateHandlers;
/// The commands which may need to handle input.
private IConsoleCommand[] InputHandlers;
/*********
** Public methods
*********/
/// The mod entry point, called after the mod is first loaded.
/// Provides simplified APIs for writing mods.
public override void Entry(IModHelper helper)
{
// register commands
this.Commands = this.ScanForCommands().ToArray();
foreach (IConsoleCommand command in this.Commands)
helper.ConsoleCommands.Add(command.Name, command.Description, (name, args) => this.HandleCommand(command, name, args));
// cache commands
this.InputHandlers = this.Commands.Where(p => p.MayNeedInput).ToArray();
this.UpdateHandlers = this.Commands.Where(p => p.MayNeedUpdate).ToArray();
// hook events
helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked;
helper.Events.Input.ButtonPressed += this.OnButtonPressed;
}
/*********
** Private methods
*********/
/// The method invoked when a button is pressed.
/// The event sender.
/// The event arguments.
private void OnButtonPressed(object sender, ButtonPressedEventArgs e)
{
foreach (IConsoleCommand command in this.InputHandlers)
command.OnButtonPressed(this.Monitor, e.Button);
}
/// The method invoked when the game updates its state.
/// The event sender.
/// The event arguments.
private void OnUpdateTicked(object sender, EventArgs e)
{
foreach (IConsoleCommand command in this.UpdateHandlers)
command.OnUpdated(this.Monitor);
}
/// Handle a console command.
/// The command to invoke.
/// The command name specified by the user.
/// The command arguments.
private void HandleCommand(IConsoleCommand command, string commandName, string[] args)
{
ArgumentParser argParser = new(commandName, args, this.Monitor);
command.Handle(this.Monitor, commandName, argParser);
}
/// Find all commands in the assembly.
private IEnumerable ScanForCommands()
{
return (
from type in this.GetType().Assembly.GetTypes()
where !type.IsAbstract && typeof(IConsoleCommand).IsAssignableFrom(type)
select (IConsoleCommand)Activator.CreateInstance(type)
);
}
}
}