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

#include <algorithm>

#include <imgui.h>

#include "projectexplorer.hpp"

namespace studio {

static ox::Result<ox::UniquePtr<ProjectTreeModel>>
buildProjectTreeModel(ProjectExplorer &explorer, ox::StringView name, ox::CRStringView path, ProjectTreeModel *parent) noexcept {
	auto const fs = explorer.romFs();
	oxRequire(stat, fs->stat(path));
	auto out = ox::make_unique<ProjectTreeModel>(explorer, ox::String(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 (auto const&childName : children) {
			if (childName[0] != '.') {
				auto const 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(turbine::Context &ctx) noexcept: m_ctx(ctx) {
}

void ProjectExplorer::draw(turbine::Context &ctx) noexcept {
	auto const viewport = ImGui::GetContentRegionAvail();
	ImGui::BeginChild("ProjectExplorer", ImVec2(300, viewport.y), true);
	ImGui::SetNextItemOpen(true);
	if (m_treeModel) {
		m_treeModel->draw(ctx);
	}
	ImGui::EndChild();
}

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

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

}
