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

#include "paletteeditor.hpp"

namespace nostalgia::core {

AddColorCommand::AddColorCommand(Palette *pal, Color16 color, int idx) noexcept {
	m_pal = pal;
	m_color = color;
	m_idx = idx;
}

int AddColorCommand::commandId() const noexcept {
	return static_cast<int>(PaletteEditorCommandId::AddColor);
}

void AddColorCommand::redo() noexcept {
	m_pal->colors.insert(static_cast<std::size_t>(m_idx), m_color);
}

void AddColorCommand::undo() noexcept {
	oxIgnoreError(m_pal->colors.erase(static_cast<std::size_t>(m_idx)));
}


RemoveColorCommand::RemoveColorCommand(Palette *pal, Color16 color, int idx) noexcept {
	m_pal = pal;
	m_color = color;
	m_idx = idx;
}

int RemoveColorCommand::commandId() const noexcept {
	return static_cast<int>(PaletteEditorCommandId::RemoveColor);
}

void RemoveColorCommand::redo() noexcept {
	oxIgnoreError(m_pal->colors.erase(static_cast<std::size_t>(m_idx)));
}

void RemoveColorCommand::undo() noexcept {
m_pal->colors.insert(static_cast<std::size_t>(m_idx), m_color);
}


UpdateColorCommand::UpdateColorCommand(Palette *pal, int idx, Color16 oldColor, Color16 newColor) noexcept {
	m_pal = pal;
	m_idx = idx;
	m_oldColor = oldColor;
	m_newColor = newColor;
	//setObsolete(m_oldColor == m_newColor);
}

bool UpdateColorCommand::mergeWith(const UndoCommand *cmd) noexcept {
	if (cmd->commandId() != static_cast<int>(PaletteEditorCommandId::UpdateColor)) {
		return false;
	}
	auto ucCmd = static_cast<const UpdateColorCommand*>(cmd);
	if (m_idx != ucCmd->m_idx) {
		return false;
	}
	m_newColor = ucCmd->m_newColor;
	return true;
}

[[nodiscard]]
int UpdateColorCommand::commandId() const noexcept {
	return static_cast<int>(PaletteEditorCommandId::UpdateColor);
}

void UpdateColorCommand::redo() noexcept {
	m_pal->colors[static_cast<std::size_t>(m_idx)] = m_newColor;
}

void UpdateColorCommand::undo() noexcept {
	m_pal->colors[static_cast<std::size_t>(m_idx)] = m_oldColor;
}


MoveColorCommand::MoveColorCommand(Palette *pal, std::size_t idx, int offset) noexcept {
	m_pal = pal;
	m_idx = idx;
	m_offset = offset;
}

int MoveColorCommand::commandId() const noexcept {
	return static_cast<int>(PaletteEditorCommandId::MoveColor);
}

void MoveColorCommand::redo() noexcept {
	moveColor(static_cast<int>(m_idx), m_offset);
}

void MoveColorCommand::undo() noexcept {
	moveColor(static_cast<int>(m_idx) + m_offset, -m_offset);
}

void MoveColorCommand::moveColor(int idx, int offset) noexcept {
	const auto c = m_pal->colors[static_cast<std::size_t>(idx)];
	oxIgnoreError(m_pal->colors.erase(static_cast<std::size_t>(idx)));
	m_pal->colors.insert(static_cast<std::size_t>(idx + offset), c);
}

}