/*
 * Copyright 2023 - 2025 Gary Talent (gary@drinkingtea.net). All rights reserved.
 */

#include "commands.hpp"
#include "addrmobjectset.hpp"

namespace jasper::world {

AddObjectSet::AddObjectSet(WorldDoc &doc, ox::UUID const &objSetUuid):
		m_doc(doc),
		m_path(ox::sfmt("uuid://{}", objSetUuid.toString())) {
	for (auto const &o : m_doc.objSets) {
		if (o.path > m_path) {
			break;
		} else if (o.path == m_path) {
			throw ox::Exception(1, "Path already exists in doc");
		}
		++m_insertIdx;
	}
}

ox::Error AddObjectSet::redo() noexcept {
	m_doc.objSets.insert(m_insertIdx, {
		.path = std::move(m_path),
		.id = ++m_doc.objSetIdIdx,
	});
	return {};
}

ox::Error AddObjectSet::undo() noexcept {
	m_path = std::move(m_doc.objSets[m_insertIdx].path);
	--m_doc.objSetIdIdx;
	return m_doc.objSets.erase(m_insertIdx).error;
}

int AddObjectSet::commandId() const noexcept {
	return static_cast<int>(WorldEditorCommand::AddObjectSet);
}


RmObjectSet::RmObjectSet(WorldDoc &doc, size_t idx):
		m_doc(doc),
		m_idx(idx) {
}

ox::Error RmObjectSet::redo() noexcept {
	m_entry = std::move(m_doc.objSets[m_idx]);
	return m_doc.objSets.erase(m_idx).error;
}

ox::Error RmObjectSet::undo() noexcept {
	m_doc.objSets.emplace(m_idx, std::move(m_entry));
	return {};
}

int RmObjectSet::commandId() const noexcept {
	return static_cast<int>(WorldEditorCommand::RmObjectSet);
}

}
