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

#include "addsubsheetcommand.hpp"

namespace nostalgia::core {

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(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);
	}
}

void 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, m_img.bpp);
	} 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, m_img.bpp);
	}
}

void 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();
	} else {
		for (auto idx = m_addedSheets.rbegin(); idx != m_addedSheets.rend(); ++idx) {
			oxLogError(rmSubSheet(m_img, *idx));
		}
	}
}

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

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

}
