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

#include <imgui.h>

#include <studio/imguiutil.hpp>
#include <utility>

#include "../filedialogmanager.hpp"
#include "newproject.hpp"

namespace studio {

NewProject::NewProject(ox::StringParam projectDatadir) noexcept:
	m_projectDataDir{std::move(projectDatadir)} {
	setTitle("New Project");
	setSize({230, 140});
}

void NewProject::open() noexcept {
	m_stage = Stage::Opening;
	m_projectPath = "";
	m_projectName = "";
}

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

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

void NewProject::draw(Context &ctx) noexcept {
	if (ImGui::IsKeyPressed(ImGuiKey_Escape)) {
		close();
		return;
	}
	switch (m_stage) {
		case Stage::Opening:
			ImGui::OpenPopup(title().c_str());
			m_stage = Stage::NewItemName;
			m_open = true;
			[[fallthrough]];
		case Stage::NewItemName:
			drawNewProjectName(ctx);
			break;
		case Stage::Closed:
			m_open = false;
			break;
	}
}

void NewProject::drawNewProjectName(Context &sctx) noexcept {
	drawWindow(sctx.tctx, m_open, [this, &sctx] {
		ig::InputText("Name", m_projectName);
		ImGui::Text("Path: %s", m_projectPath.c_str());
		if (ig::PushButton("Browse")) {
			oxLogError(studio::chooseDirectory().moveTo(m_projectPath));
		}
		drawLastPageButtons(sctx);
	});
}

void NewProject::drawLastPageButtons(Context&) noexcept {
	auto const scale = ig::dpiScale();
	ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - 110 * scale);
	ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ImGui::GetContentRegionAvail().y - 22 * scale);
	if (ig::PushButton("Finish")) {
		finish();
	}
	ImGui::SameLine();
	if (ig::PushButton("Quit")) {
		ImGui::CloseCurrentPopup();
		m_stage = Stage::Closed;
	}
}

void NewProject::finish() noexcept {
	auto projectPath = ox::sfmt("{}/{}", m_projectPath, m_projectName);
	finished.emit(projectPath);
	m_stage = Stage::Closed;
}

}
