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

#include <studio/imguiutil.hpp>

#include "makecopy.hpp"

namespace studio {

ox::Error MakeCopyPopup::open(ox::StringViewCR path) noexcept {
	m_stage = Stage::Opening;
	OX_REQUIRE(idx, ox::findIdx(path.rbegin(), path.rend(), '/'));
	m_srcPath = path;
	m_dirPath = substr(path, 0, idx + 1);
	m_title = sfmt("Copy {}", path);
	m_fileName = "";
	m_errMsg = "";
	return {};
}

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

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

void MakeCopyPopup::draw(Context &ctx) noexcept {
	switch (m_stage) {
		case Stage::Closed:
			break;
		case Stage::Opening:
			ImGui::OpenPopup(m_title.c_str());
			m_stage = Stage::Open;
			m_open = true;
		[[fallthrough]];
		case Stage::Open: {
			auto const scale = ig::dpiScale();
			ig::centerNextWindow();
			ImGui::SetNextWindowSize({250 * scale, 0});
			constexpr auto modalFlags =
				ImGuiWindowFlags_NoCollapse |
				ImGuiWindowFlags_NoMove |
				ImGuiWindowFlags_NoResize;
			if (ImGui::BeginPopupModal(m_title.c_str(), &m_open, modalFlags)) {
				if (ImGui::IsWindowAppearing()) {
					ImGui::SetKeyboardFocusHere();
				}
				ig::InputText("Name", m_fileName);
				if (ImGui::IsItemFocused() && ImGui::IsKeyPressed(ImGuiKey_Enter)) {
					accept(ctx);
				}
				ImGui::Text("%s", m_errMsg.c_str());
				bool open = true;
				switch (ig::PopupControlsOkCancel(open)) {
					case ig::PopupResponse::None:
						break;
					case ig::PopupResponse::OK:
						accept(ctx);
						break;
					case ig::PopupResponse::Cancel:
						close();
						break;
				}
				ImGui::EndPopup();
			}
			break;
		}
	}
}

void MakeCopyPopup::accept(Context const &ctx) noexcept {
	auto const p = sfmt("{}{}", m_dirPath, m_fileName);
	if (!ctx.project->exists(p)) {
		makeCopy.emit(m_srcPath, p);
		close();
	} else {
		m_errMsg = sfmt("{} already exists", p);
	}
}

}
