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

#include "addsubsheetcommand.hpp"

namespace nostalgia::gfx {

AddSubSheetCommand::AddSubSheetCommand(
		TileSheet &img,
		TileSheet::SubSheetIdx parentIdx) noexcept:
		m_img(img), m_parentIdx(std::move(parentIdx)) {
	auto &parent = getSubSheet(m_img, m_parentIdx);
	if (!parent.subsheets.empty()) {
		auto idx = m_parentIdx;
		idx.emplace_back(static_cast<uint32_t>(parent.subsheets.size()));
		m_addedSheets.push_back(idx);
	} else {
		auto idx = m_parentIdx;
		idx.emplace_back(0u);
		m_addedSheets.push_back(idx);
		*idx.back().value = 1;
		m_addedSheets.push_back(idx);
	}
}

ox::Error AddSubSheetCommand::redo() noexcept {
	auto &parent = getSubSheet(m_img, m_parentIdx);
	if (m_addedSheets.size() < 2) {
		auto i = parent.subsheets.size();
		parent.subsheets.emplace_back(m_img.idIt++, ox::sfmt("Subsheet {}", i), 1, 1);
	} else {
		parent.subsheets.emplace_back(m_img.idIt++, "Subsheet 0", parent.columns, parent.rows, std::move(parent.pixels));
		parent.rows = 0;
		parent.columns = 0;
		parent.subsheets.emplace_back(m_img.idIt++, "Subsheet 1", 1, 1);
	}
	return {};
}

ox::Error AddSubSheetCommand::undo() noexcept {
	auto &parent = getSubSheet(m_img, m_parentIdx);
	if (parent.subsheets.size() == 2) {
		auto s = parent.subsheets[0];
		parent.rows = s.rows;
		parent.columns = s.columns;
		parent.pixels = std::move(s.pixels);
		parent.subsheets.clear();
		--m_img.idIt;
	} else {
		for (auto idx = m_addedSheets.rbegin(); idx != m_addedSheets.rend(); ++idx) {
			OX_RETURN_ERROR(rmSubSheet(m_img, *idx));
			--m_img.idIt;
		}
	}
	return {};
}

int AddSubSheetCommand::commandId() const noexcept {
	return static_cast<int>(CommandId::AddSubSheet);
}

TileSheet::SubSheetIdx const &AddSubSheetCommand::subsheetIdx() const noexcept {
	return m_parentIdx;
}

}
