#include "SafeWalk.h"
#include "Utils/MoveUtils.h"

auto SafeWalk::onWorldTick(Player* _this) -> void {
    if (Utils::Move::isOnGround(_this)) {
        if (!patched) {

            DWORD oldProtect;
            VirtualProtect((void*)sneakmovementsystem_tick_, 2, PAGE_EXECUTE_READWRITE, &oldProtect);
            memcpy(ogBytes, (void*)sneakmovementsystem_tick_, 2);
            VirtualProtect((void*)sneakmovementsystem_tick_, 2, oldProtect, &oldProtect);

            VirtualProtect((LPVOID)sneakmovementsystem_tick_, 2, PAGE_EXECUTE_READWRITE, &oldProtect);
            memcpy((LPVOID)sneakmovementsystem_tick_, _("\x90\x90"), 2);
            VirtualProtect((LPVOID)sneakmovementsystem_tick_, 2, oldProtect, &oldProtect);

            patched = true;
        }
    }
    else {
        if (patched) {
            DWORD oldProtect;
            VirtualProtect((LPVOID)sneakmovementsystem_tick_, 2, PAGE_EXECUTE_READWRITE, &oldProtect);
            memcpy((LPVOID)sneakmovementsystem_tick_, ogBytes, 2);
            VirtualProtect((LPVOID)sneakmovementsystem_tick_, 2, oldProtect, &oldProtect);

            patched = false;
        }
    }
}

auto SafeWalk::onDisabled() -> void {
    if (patched) {
        DWORD oldProtect;
        VirtualProtect((LPVOID)sneakmovementsystem_tick_, 2, PAGE_EXECUTE_READWRITE, &oldProtect);
        memcpy((LPVOID)sneakmovementsystem_tick_, ogBytes, 2);
        VirtualProtect((LPVOID)sneakmovementsystem_tick_, 2, oldProtect, &oldProtect);

        patched = false;
    }
}
