// -----------------------------------------------------------------------------
// console.cpp
// -----------------------------------------------------------------------------
// Implementation of console helpers: colored output, window placement and a
// randomized window title (helps avoid trivial window-scanning detections).
// -----------------------------------------------------------------------------

#include "console.h"

#include <windows.h>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>

namespace util {

// Sets the console text color for the given handle.
static void SetColor(Color color)
{
	HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleTextAttribute(console, static_cast<unsigned short>(color));
}

void PrintColored(Color color, const std::string& text)
{
	SetColor(color);
	std::cout << text;
	SetColor(Color::Default);
}

void PrintText(const char* color, const std::string& text)
{
	Color resolved = Color::Default;
	if (strcmp(color, "red") == 0) { resolved = Color::Red; }
	else if (strcmp(color, "green") == 0) { resolved = Color::Green; }
	else if (strcmp(color, "aqua") == 0) { resolved = Color::Aqua; }
	else if (strcmp(color, "blue") == 0) { resolved = Color::Blue; }
	PrintColored(resolved, text);
}

void PrepareConsole()
{
	SetConsoleCP(CP_UTF8);
	SetConsoleOutputCP(CP_UTF8);
	HWND window = GetConsoleWindow();
	if (window != nullptr) {
		MoveWindow(window, 100, 100, 375, 250, TRUE);
	}

	static const char kChars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	srand(static_cast<unsigned>(time(nullptr)));
	std::string title;
	for (int i = 0; i < 10; i++)
		title += kChars[rand() % (sizeof(kChars) - 1)];
	SetConsoleTitleA(title.c_str());
}

} // namespace util
