using System;
using System.Diagnostics.CodeAnalysis;
using HarmonyLib;
using StardewModdingAPI.Framework.Patching;
using StardewValley;
namespace StardewModdingAPI.Patches
{
/// A Harmony patch for the constructor which intercepts invalid dialogue lines and logs an error instead of crashing.
/// Patch methods must be static for Harmony to work correctly. See the Harmony documentation before renaming patch arguments.
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony and methods are named for clarity.")]
[SuppressMessage("ReSharper", "IdentifierTypo", Justification = "Argument names are defined by Harmony and methods are named for clarity.")]
internal class EventErrorPatch : IHarmonyPatch
{
/*********
** Fields
*********/
/// Writes messages to the console and log file on behalf of the game.
private static IMonitor MonitorForGame;
/*********
** Accessors
*********/
/// A unique name for this patch.
public string Name => nameof(EventErrorPatch);
/*********
** Public methods
*********/
/// Construct an instance.
/// Writes messages to the console and log file on behalf of the game.
public EventErrorPatch(IMonitor monitorForGame)
{
EventErrorPatch.MonitorForGame = monitorForGame;
}
/// Apply the Harmony patch.
/// The Harmony instance.
public void Apply(Harmony harmony)
{
harmony.Patch(
original: AccessTools.Method(typeof(GameLocation), "checkEventPrecondition"),
finalizer: new HarmonyMethod(this.GetType(), nameof(EventErrorPatch.Finalize_GameLocation_CheckEventPrecondition))
);
}
/*********
** Private methods
*********/
/// The method to call instead of the GameLocation.CheckEventPrecondition.
/// The return value of the original method.
/// The precondition to be parsed.
/// The exception thrown by the wrapped method, if any.
/// Returns the exception to throw, if any.
private static Exception Finalize_GameLocation_CheckEventPrecondition(ref int __result, string precondition, Exception __exception)
{
if (__exception != null)
{
__result = -1;
EventErrorPatch.MonitorForGame.Log($"Failed parsing event precondition ({precondition}):\n{__exception.InnerException}", LogLevel.Error);
}
return null;
}
}
}