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

#include <studio/imguiutil.hpp>

#include "newdir.hpp"

namespace studio {

NewDir::NewDir() noexcept {
	setTitle("New Directory");
	setSize({280, 0});
}

void NewDir::openPath(ox::StringViewCR path) noexcept {
	open();
	m_path = path;
}

void NewDir::open() noexcept {
	m_path = "";
	m_stage = Stage::Opening;
}

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

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

void NewDir::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_stage = Stage::Open;
		[[fallthrough]];
		case Stage::Open:
			drawWindow(ctx.tctx, m_open, [this] {
				if (ImGui::IsWindowAppearing()) {
					ImGui::SetKeyboardFocusHere();
				}
				ig::InputText("Name", m_str);
				ImGui::SetItemDefaultFocus();
				if (ImGui::IsItemFocused() && ImGui::IsKeyPressed(ImGuiKey_Enter)) {
					newDir.emit(m_path + "/" + m_str);
					close();
				}
				if (ig::PopupControlsOkCancel(m_open) == ig::PopupResponse::OK) {
					newDir.emit(m_path + "/" + m_str);
					close();
				}
			});
			break;
	}
}

}
