#define _CRT_SECURE_NO_WARNINGS
#include "MenuParams.h"
#include <algorithm>
#include <cstdio>

// 全局菜单参数实例
CMenuParams MenuParams;

void CMenuParams::GetFilePath(char* buf, int bufSize) const
{
	GetCurrentDirectoryA(bufSize, buf);
	sprintf_s(buf, bufSize, "%s\\configs\\menu.configs", buf);
}

void CMenuParams::Load()
{
	// 读取 AutoLoad 开关
	char path[MAX_PATH];
	GetFilePath(path, MAX_PATH);
	this->AutoLoad = GetPrivateProfileIntA("Menu", "AutoLoad", 1, path) != 0;

	if (this->AutoLoad)
	{
		// 从 menu.cfg 读取布局参数
		this->PosX   = (float)GetPrivateProfileIntA("Menu", "PosX",   100, path);
		this->PosY   = (float)GetPrivateProfileIntA("Menu", "PosY",   100, path);
		this->Width  = (float)GetPrivateProfileIntA("Menu", "Width",  660, path);
		this->Height = (float)GetPrivateProfileIntA("Menu", "Height", 560, path);

		// 确保宽高合法
		this->Width  = std::max(this->Width,  200.0f);
		this->Height = std::max(this->Height, 200.0f);
	}
	// AutoLoad=false: 使用类成员默认值 (PosX=100, PosY=100, Width=660, Height=560)
}

void CMenuParams::Save(const GamesenseMenuFramework::Vec2& pos, const GamesenseMenuFramework::Vec2& size)
{
	char path[MAX_PATH];
	GetFilePath(path, MAX_PATH);

	char buf[32];

	// AutoLoad 开关（仅变化时写入）
	int oldAuto = GetPrivateProfileIntA("Menu", "AutoLoad", -1, path);
	int newAuto = this->AutoLoad ? 1 : 0;
	if (oldAuto != newAuto)
	{
		_itoa(newAuto, buf, 10);
		WritePrivateProfileStringA("Menu", "AutoLoad", buf, path);
	}

	// 位置/大小（仅变化时写入，避免每帧无意义 IO）
	int oldX = GetPrivateProfileIntA("Menu", "PosX",  -1, path);
	int oldY = GetPrivateProfileIntA("Menu", "PosY",  -1, path);
	int oldW = GetPrivateProfileIntA("Menu", "Width",  -1, path);
	int oldH = GetPrivateProfileIntA("Menu", "Height", -1, path);

	if (oldX != (int)pos.x)  { _itoa((int)pos.x,  buf, 10); WritePrivateProfileStringA("Menu", "PosX",  buf, path); }
	if (oldY != (int)pos.y)  { _itoa((int)pos.y,  buf, 10); WritePrivateProfileStringA("Menu", "PosY",  buf, path); }
	if (oldW != (int)size.x) { _itoa((int)size.x, buf, 10); WritePrivateProfileStringA("Menu", "Width",  buf, path); }
	if (oldH != (int)size.y) { _itoa((int)size.y, buf, 10); WritePrivateProfileStringA("Menu", "Height", buf, path); }

	// 同步到成员变量
	this->PosX   = pos.x;
	this->PosY   = pos.y;
	this->Width  = size.x;
	this->Height = size.y;
}

GamesenseMenuFramework::Vec2 CMenuParams::GetSize() const
{
	return GamesenseMenuFramework::Vec2(this->Width, this->Height);
}

GamesenseMenuFramework::Vec2 CMenuParams::GetPos() const
{
	return GamesenseMenuFramework::Vec2(this->PosX, this->PosY);
}
