/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#include "Drawable.hpp"
#include "Scene.hpp"
#include "Base/Utils.hpp"

namespace OpenVulkano::Scene
{
	void Drawable::Close()
	{
		SetScene(nullptr);
		for (auto& node : m_nodes)
		{ // unregister from nodes
			Utils::Remove(node->drawables, this);
		}
		m_nodes.clear();
		m_shader = nullptr;
	}

	void Drawable::SetScene(Scene* scene)
	{
		if (m_scene == scene) return;
		if (scene && m_scene) throw std::runtime_error("Drawable has been associated with a scene already!");
		const auto oldScene = m_scene;
		m_scene = scene;
		if (scene) scene->RegisterDrawable(this);
		if (oldScene) oldScene->RemoveDrawable(this);
	}

	void Drawable::AddNode(Node* node)
	{
		if (Utils::Contains(m_nodes, node)) throw std::runtime_error("A drawable must not use the same node more than once.");
		m_nodes.push_back(node);
	}

	void Drawable::RemoveNode(Node* node)
	{
		Utils::Remove(m_nodes, node);
		if (m_nodes.empty() && m_scene)
		{
			m_scene->RemoveDrawable(this);
			m_scene = nullptr;
		}
	}
}
