using System.Reflection;
using Celeste.Mod.Entities;
using Celeste.Mod.Helpers;
using Monocle;
using MonoMod.Cil;

namespace Celeste.Mod.SuperheatedSuperstructure.Entities {
    [Tracked(false)]
    [CustomEntity($"{nameof(SuperheatedSuperstructure)}/{nameof(NoStaminaFlashController)}")]
    public class NoStaminaFlashController : Entity {
        private static readonly FieldInfo f_Player_flash = typeof(Player)
            .GetField("flash", BindingFlags.NonPublic | BindingFlags.Instance);

        public static void Load() {
            IL.Celeste.Player.Render += patch_Player_Render;
        }

        public static void Unload() {
            IL.Celeste.Player.Render -= patch_Player_Render;
        }

        private static void patch_Player_Render(ILContext il) {
            var cursor = new ILCursor(il);

            if(!cursor.TryGotoNextBestFit(MoveType.After,
                instr => instr.MatchLdarg0(),
                instr => instr.MatchLdfld(f_Player_flash)
            )) {
                Logger.Debug(nameof(SuperheatedSuperstructureModule), "failed to find Player.flash in Player.Render!");

                return;
            }

            cursor.EmitDelegate(overrideFlash);
        }

        private static bool overrideFlash(bool orig)
            => Engine.Scene.Tracker.GetEntity<NoStaminaFlashController>() is {}
                ? false
                : orig;
    }
}