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

#include <algorithm>

#include <imgui.h>

#include <nostalgia/geo/bounds.hpp>

#include "projectexplorer.hpp"

namespace nostalgia {

static ox::Result<ox::UniquePtr<ProjectTreeModel>>
buildProjectTreeModel(ProjectExplorer *explorer, const ox::String &name, const ox::String &path, ProjectTreeModel *parent) noexcept {
	const auto fs = explorer->romFs();
	oxRequire(stat, fs->stat(path.c_str()));
	auto out = ox::make_unique<ProjectTreeModel>(explorer, name, parent);
	if (stat.fileType == ox::FileType::Directory) {
		oxRequireM(children, fs->ls(path));
		std::sort(children.begin(), children.end());
		ox::Vector<ox::UniquePtr<ProjectTreeModel>> outChildren;
		for (const auto &childName : children) {
			if (childName[0] != '.') {
				const auto childPath = ox::sfmt("{}/{}", path, childName);
				oxRequireM(child, buildProjectTreeModel(explorer, childName, childPath, out.get()));
				outChildren.emplace_back(std::move(child));
			}
		}
		out->setChildren(std::move(outChildren));
	}
	return out;
}

ProjectExplorer::ProjectExplorer(core::Context *ctx) noexcept {
	m_ctx = ctx;
}

void ProjectExplorer::draw(core::Context *ctx) noexcept {
	const auto viewport = ImGui::GetMainViewport();
	ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + 20));
	ImGui::SetNextWindowSize(ImVec2(313, viewport->Size.y - 20));
	const auto flags = ImGuiWindowFlags_NoTitleBar
	                 | ImGuiWindowFlags_NoResize
	                 | ImGuiWindowFlags_NoMove
	                 | ImGuiWindowFlags_NoScrollbar
	                 | ImGuiWindowFlags_NoSavedSettings;
	ImGui::Begin("ProjectExplorer", nullptr, flags);
	ImGui::SetNextItemOpen(true);
	if (m_treeModel) {
		m_treeModel->draw(ctx);
	}
	ImGui::End();
}

void ProjectExplorer::setModel(ox::UniquePtr<ProjectTreeModel> model) noexcept {
	m_treeModel = std::move(model);
}

ox::Error ProjectExplorer::refreshProjectTreeModel(const ox::String&) noexcept {
	oxRequireM(model, buildProjectTreeModel(this, "Project", "/", nullptr));
	setModel(std::move(model));
	return OxError(0);
}

}

