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

#include <algorithm>

#include "commands.hpp"
#include "addpalette.hpp"

#include <keel/media.hpp>

namespace jasper::world {

AddPalette::AddPalette(WorldObjectSet &doc, ox::FileAddress palAddr) noexcept:
	m_doc{doc},
	m_palAddr{std::move(palAddr)} {
}

ox::Error AddPalette::redo() noexcept {
	m_doc.palettes.emplace_back(m_palAddr);
	//std::sort(m_doc.palettes.begin(), m_doc.palettes.end(),
	//	[this](ox::FileAddress const &a, ox::FileAddress const &b) {
	//		auto const aPath = uuidUrlToPath(m_kctx, a.getPath().or_value("")).or_value("");
	//		auto const bPath = uuidUrlToPath(m_kctx, b.getPath().or_value("")).or_value("");
	//		return aPath < bPath;
	//	});
	return {};
}

ox::Error AddPalette::undo() noexcept {
	auto const idx = std::find_if(m_doc.palettes.begin(), m_doc.palettes.end(),
		[this](ox::FileAddress const &v) {
			return v == m_palAddr;
		});
	return m_doc.palettes.erase(idx).error;
}

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

}
