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

#include <algorithm>

#include "commands.hpp"
#include "rmpalette.hpp"

namespace jasper::world {

RmPalette::RmPalette(WorldObjectSet &doc, size_t const rmIdx) noexcept:
		m_doc(doc),
		m_rmIdx(rmIdx) {
	m_objUpdates.reserve(m_doc.objects.size());
	for (size_t i = 0; auto const &obj : m_doc.objects) {
		if (obj.palBank >= m_rmIdx) {
			uint8_t const newPalBank = obj.palBank == m_rmIdx ?
				0 : obj.palBank - 1;
			m_objUpdates.emplace_back(ObjUpdate{
				.idx = i,
				.oldPalBank = obj.palBank,
				.newPalBank = newPalBank,
			});
		}
		++i;
	}
}

ox::Error RmPalette::redo() noexcept {
	m_pal = std::move(m_doc.palettes[m_rmIdx]);
	std::ignore = m_doc.palettes.erase(m_rmIdx);
	for (auto const &u : m_objUpdates) {
		m_doc.objects[u.idx].palBank = u.newPalBank;
	}
	return {};
}

ox::Error RmPalette::undo() noexcept {
	m_doc.palettes.emplace_back(std::move(m_pal));
	std::sort(m_doc.palettes.begin(), m_doc.palettes.end(),
		[](ox::FileAddress const &a, ox::FileAddress const &b) {
			return a.getPath().or_value("") < b.getPath().or_value("");
		});
	for (auto const &u : m_objUpdates) {
		m_doc.objects[u.idx].palBank = u.oldPalBank;
	}
	return {};
}

int RmPalette::commandId() const noexcept {
	return static_cast<int>(WorldObjCommand::RmPalette);
}

}
