/*
 * Copyright 2016 - 2024 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::String projectDatadir) noexcept: m_projectDataDir(std::move(projectDatadir)) {
	setTitle(ox::String("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(studio::StudioContext &ctx) noexcept {
	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(studio::StudioContext &sctx) noexcept {
	drawWindow(sctx.tctx, &m_open, [this, &sctx] {
		ImGui::InputText("Name", m_projectName.data(), m_projectName.cap());
		ImGui::Text("Path: %s", m_projectPath.c_str());
		if (ImGui::Button("Browse")) {
			oxLogError(studio::chooseDirectory().moveTo(m_projectPath));
		}
		drawLastPageButtons(sctx);
	});
}

void NewProject::drawFirstPageButtons() noexcept {
	ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - 130);
	ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ImGui::GetContentRegionAvail().y - 20);
	auto const btnSz = ImVec2(60, 20);
	if (ImGui::Button("Next", btnSz)) {
		m_stage = Stage::NewItemName;
	}
	ImGui::SameLine();
	if (ImGui::Button("Cancel", btnSz)) {
		ImGui::CloseCurrentPopup();
		m_stage = Stage::Closed;
	}
}

void NewProject::drawLastPageButtons(studio::StudioContext&) noexcept {
	ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - 95);
	ImGui::SetCursorPosY(ImGui::GetCursorPosY() + ImGui::GetContentRegionAvail().y - 20);
	if (ImGui::Button("Finish")) {
		finish();
	}
	ImGui::SameLine();
	if (ImGui::Button("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;
}

}
