#include "ItemStateRegistry.hpp"
#include <OgreLogManager.h>
#include <fstream>

ItemStateRegistry &ItemStateRegistry::getInstance()
{
	static ItemStateRegistry instance;
	return instance;
}

ItemStateRegistry::ItemStateRegistry()
{
	m_autoSavePath = "item_state.json";
}

void ItemStateRegistry::setDisabled(const std::string &instanceId,
				    bool disabled)
{
	if (instanceId.empty())
		return;
	ItemState &state = m_states[instanceId];
	state.instanceId = instanceId;
	state.disabled = disabled;
	autoSave();
}

bool ItemStateRegistry::isDisabled(const std::string &instanceId) const
{
	if (instanceId.empty())
		return false;
	auto it = m_states.find(instanceId);
	if (it != m_states.end())
		return it->second.disabled;
	return false;
}

void ItemStateRegistry::clearState(const std::string &instanceId)
{
	m_states.erase(instanceId);
	autoSave();
}

nlohmann::json ItemStateRegistry::serialize() const
{
	nlohmann::json j;
	j["version"] = "1.0";
	for (const auto &pair : m_states) {
		const ItemState &state = pair.second;
		nlohmann::json stateJson;
		stateJson["instanceId"] = state.instanceId;
		stateJson["disabled"] = state.disabled;
		j["states"].push_back(stateJson);
	}
	return j;
}

void ItemStateRegistry::deserialize(const nlohmann::json &j)
{
	m_states.clear();
	if (!j.contains("states"))
		return;
	for (const auto &stateJson : j["states"]) {
		ItemState state;
		state.instanceId = stateJson.value("instanceId", "");
		state.disabled = stateJson.value("disabled", false);
		if (!state.instanceId.empty())
			m_states[state.instanceId] = state;
	}
}

bool ItemStateRegistry::saveToFile(const std::string &filepath)
{
	try {
		std::ofstream file(filepath);
		if (!file.is_open()) {
			m_lastError = "Cannot open " + filepath;
			return false;
		}
		file << serialize().dump(4);
		return true;
	} catch (const std::exception &e) {
		m_lastError = std::string("Save error: ") + e.what();
		return false;
	}
}

bool ItemStateRegistry::loadFromFile(const std::string &filepath)
{
	try {
		std::ifstream file(filepath);
		if (!file.is_open()) {
			m_lastError = "Cannot open " + filepath;
			return false;
		}
		nlohmann::json j;
		file >> j;
		deserialize(j);
		return true;
	} catch (const std::exception &e) {
		m_lastError = std::string("Load error: ") + e.what();
		return false;
	}
}

void ItemStateRegistry::autoSave()
{
	if (!m_autoSavePath.empty())
		saveToFile(m_autoSavePath);
}
