#include "client/config/BlitzConfig.h"

#include "blitz/misc/Log.h"
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

namespace blitz {

BlitzConfig::BlitzConfig() {
	LoadConfig();
}

BlitzConfig::~BlitzConfig() {
	SaveConfig();
}

void BlitzConfig::LoadConfig() {
	std::ifstream file{"settings.json"};

	LoadDefaultConfig();

	if (!file) {
		utils::LOG("Could not load config !");
		return;
	}

	try {
		json jsonInput;
		file >> jsonInput;

		std::string pseudo;
		jsonInput.find("pseudo");
		jsonInput.at("pseudo").get_to<std::string>(pseudo);
		std::memcpy(m_Pseudo.data(), pseudo.data(), pseudo.size() + 1);
		jsonInput.at("vsync").get_to<bool>(m_VSync);
		jsonInput.at("fps").get_to<bool>(m_DisplayFps);
	} catch (std::exception& e) {
		utils::LOGE("Failed to load config !");
	}
}

void BlitzConfig::LoadDefaultConfig() {
	m_DisplayFps = false;
	m_VSync = true;
	const char defaultPseudo[] = "Pseudo";
	std::memcpy(m_Pseudo.data(), defaultPseudo, sizeof(defaultPseudo));
}

void BlitzConfig::SaveConfig() {
	std::ofstream file{"settings.json"};

	if (!file) {
		utils::LOGE("Could not save config !");
	}

	json jsonOutput = {
		{"pseudo", GetPseudo().data()},
		{"vsync", IsVSyncEnabled()},
		{"fps", IsFPSDisplayEnabled()},
	};

	file << jsonOutput;
}

}  // namespace blitz
