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

#include "cutpastecommand.hpp"

namespace nostalgia::core {

TileSheetClipboard::Pixel::Pixel(uint16_t pColorIdx, ox::Point pPt) noexcept {
	colorIdx = pColorIdx;
	pt = pPt;
}


void TileSheetClipboard::addPixel(const ox::Point &pt, uint16_t colorIdx) noexcept {
	m_pixels.emplace_back(colorIdx, pt);
}

const ox::Vector<TileSheetClipboard::Pixel> &TileSheetClipboard::pixels() const noexcept {
	return m_pixels;
}


CutPasteCommand::CutPasteCommand(
		CommandId commandId,
		TileSheet &img,
		TileSheet::SubSheetIdx subSheetIdx,
		const ox::Point &dstStart,
		const ox::Point &dstEnd,
		const TileSheetClipboard &cb) noexcept:
		m_commandId(commandId),
		m_img(img),
		m_subSheetIdx(std::move(subSheetIdx)) {
	const auto &subsheet = getSubSheet(m_img, m_subSheetIdx);
	for (const auto &p : cb.pixels()) {
		const auto dstPt = p.pt + dstStart;
		if (dstPt.x <= dstEnd.x && dstPt.y <= dstEnd.y) {
			const auto idx = core::idx(subsheet, dstPt);
			m_changes.emplace_back(static_cast<uint32_t>(idx), p.colorIdx, getPixel(subsheet, m_img.bpp, idx));
		}
	}
}

void CutPasteCommand::redo() noexcept {
	auto &subsheet = getSubSheet(m_img, m_subSheetIdx);
	for (const auto &c : m_changes) {
		setPixel(subsheet, m_img.bpp, c.idx, static_cast<uint8_t>(c.newPalIdx));
	}
}

void CutPasteCommand::undo() noexcept {
	auto &subsheet = getSubSheet(m_img, m_subSheetIdx);
	for (const auto &c : m_changes) {
		setPixel(subsheet, m_img.bpp, c.idx, static_cast<uint8_t>(c.oldPalIdx));
	}
}

int CutPasteCommand::commandId() const noexcept {
	return static_cast<int>(m_commandId);
}

TileSheet::SubSheetIdx const&CutPasteCommand::subsheetIdx() const noexcept {
	return m_subSheetIdx;
}

}
