// -----------------------------------------------------------------------------
// noflash.cpp
// -----------------------------------------------------------------------------
// Implementation of the no-flash feature. The thread polls the toggle every
// frame and writes the flash alpha value to the local pawn directly, so the
// effect applies even when the player is flashed mid-round.
// -----------------------------------------------------------------------------

#include "noflash.h"

#include <windows.h>
#include <sstream>

#include "../config.h"
#include "../util/logger.h"

namespace features {

void NoFlash::Initialize(const core::ProcessMemory* memory, const core::GameOffsets* offsets,
	const sdk::LocalPlayer* player)
{
	m_memory = memory;
	m_offsets = offsets;
	m_player = player;
}

void NoFlash::Start()
{
	CreateThread(nullptr, 0, &NoFlash::ThreadProc, this, 0, nullptr);
}

unsigned long __stdcall NoFlash::ThreadProc(void* param)
{
	NoFlash* self = static_cast<NoFlash*>(param);
	if (self == nullptr) {
		return 1;
	}

	if (self->m_offsets->flashMaxAlpha == 0) {
		util::LogFatal("[noflash] m_flFlashMaxAlpha unresolved, feature disabled");
		return 1;
	}

	while (true) {
		const bool enabled = cfg::g_config.noFlashEnabled;

		if (!enabled && !self->m_lastEnabled) {
			Sleep(250);
			continue;
		}

		const uintptr_t pawn = self->m_player->GetLocalPawn();
		if (pawn != 0) {
			float alpha = -1.0f;
			if (enabled) {
				alpha = 0.0f;
			} else if (self->m_lastEnabled) {
				alpha = 255.0f;
			}

			if (alpha >= 0.0f) {
				std::stringstream ss;
				ss << "[noflash] write alpha=" << alpha << " pawn=0x" << std::hex << pawn
					<< " addr=0x" << (pawn + self->m_offsets->flashMaxAlpha);
				util::LogDebug(ss.str());
				self->m_memory->Write<float>(pawn + self->m_offsets->flashMaxAlpha, alpha);
			}
		}
		self->m_lastEnabled = enabled;
		Sleep(10);
	}
	return 0;
}

} // namespace features