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

#include <imgui.h>

#include "projectexplorer.hpp"
#include "projecttreemodel.hpp"

namespace nostalgia {

ProjectTreeModel::ProjectTreeModel(ProjectExplorer *explorer, const ox::String &name,
                                   ProjectTreeModel *parent) noexcept {
	m_explorer = explorer;
	m_name = name;
	m_parent = parent;
}

ProjectTreeModel::ProjectTreeModel(ProjectTreeModel &&other) noexcept {
	m_name = std::move(other.m_name);
	m_children = std::move(other.m_children);
}

void ProjectTreeModel::draw(core::Context *ctx) noexcept {
	constexpr auto dirFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;
	if (m_children.size()) {
		if (ImGui::TreeNodeEx(m_name.c_str(), dirFlags)) {
			for (auto &child : m_children) {
				child->draw(ctx);
			}
			ImGui::TreePop();
		}
	} else if (auto path = fullPath(); ImGui::TreeNodeEx(ox::sfmt("{}##{}", m_name, path).c_str(), ImGuiTreeNodeFlags_Leaf)) {
		if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) {
			m_explorer->fileChosen.emit(path);
		}
		ImGui::TreePop();
	}
}

void ProjectTreeModel::setChildren(ox::Vector<ox::UniquePtr<ProjectTreeModel>> children) noexcept {
	m_children = std::move(children);
}

ox::String ProjectTreeModel::fullPath() noexcept {
	if (m_parent) {
		return m_parent->fullPath() + "/" + m_name;
	}
	return "";
}

}