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

#include <studio/imguiutil.hpp>

#include "renamefile.hpp"

namespace studio {

RenameFile::RenameFile() {
	setTitle("Rename File");
}

ox::Error RenameFile::openPath(ox::StringParam path) noexcept {
	m_oldPath = std::move(path);
	OX_REQUIRE(idx, ox::findIdx(m_oldPath.rbegin(), m_oldPath.rend(), '/'));
	m_name = substr(m_oldPath, idx + 1);
	m_path = substr(m_oldPath, 0, idx + 1);
	open();
	return {};
}

void RenameFile::open() noexcept {
	m_stage = Stage::Opening;
}

void RenameFile::close() noexcept {
	m_stage = Stage::Closed;
	m_open = false;
}

bool RenameFile::isOpen() const noexcept {
	return m_open;
}

void RenameFile::draw(Context &ctx) noexcept {
	if (ImGui::IsKeyPressed(ImGuiKey_Escape)) {
		close();
		return;
	}
	switch (m_stage) {
		case Stage::Closed:
			break;
		case Stage::Opening:
			ImGui::OpenPopup(title().c_str());
			m_open = true;
			m_fileExists = false;
			m_stage = Stage::Open;
		[[fallthrough]];
		case Stage::Open:
			setSize({250, 0});
			drawWindow(ctx.tctx, m_open, [this, &ctx] {
				if (ImGui::IsWindowAppearing()) {
					ImGui::SetKeyboardFocusHere();
				}
				m_fileExists = !ig::InputText("Name", m_name) && m_fileExists;
				auto const nameInputFocused = ImGui::IsItemFocused();
				if (m_fileExists) {
					ImGui::Text("File %s already exists.", m_name.c_str());
				} else {
					ImGui::Text("%s%s", m_path.c_str(), m_name.c_str());
				}
				bool b{};
				auto const response = ig::PopupControlsOkCancel(b);
				if (response == ig::PopupResponse::OK ||
				    (nameInputFocused && ImGui::IsKeyPressed(ImGuiKey_Enter))) {
					auto const newPath = m_path + m_name;
					if (!ctx.project->exists(newPath)) {
						moveFile.emit(m_oldPath, newPath);
						close();
					} else {
						m_open = true;
						m_fileExists = true;
					}
				} else if (response == ig::PopupResponse::Cancel) {
					close();
				}
			});
			break;
	}
}

}