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

#include "commands.hpp"
#include "applycolorallpagescommand.hpp"

namespace nostalgia::gfx {

ApplyColorAllPagesCommand::ApplyColorAllPagesCommand(Palette &pal, size_t const page, size_t const idx):
	m_pal(pal),
	m_page(page),
	m_idx(idx),
	m_origColors([this] {
		ox::Vector<Color16> colors;
		colors.reserve(m_pal.pages.size());
		for (auto const&p : m_pal.pages) {
			colors.emplace_back(p.colors[m_idx]);
		}
		return colors;
	}()) {
	auto const c = color(m_pal, m_page, m_idx);
	if (ox::all_of(m_pal.pages.begin(), m_pal.pages.end(), [this, c](PalettePage const&page) {
			return page.colors[m_idx] == c;
		})) {
		throw studio::NoChangesException();
	}
}

int ApplyColorAllPagesCommand::commandId() const noexcept {
	return static_cast<int>(PaletteEditorCommandId::ApplyColorAllPages);
}

ox::Error ApplyColorAllPagesCommand::redo() noexcept {
	auto const c = color(m_pal, m_page, m_idx);
	for (auto &page : m_pal.pages) {
		page.colors[m_idx] = c;
	}
	return {};
}

ox::Error ApplyColorAllPagesCommand::undo() noexcept {
	for (size_t p = 0u; auto &page : m_pal.pages) {
		page.colors[m_idx] = m_origColors[p];
		++p;
	}
	return {};
}

}