#include "MiniginPCH.h"
#include "RenderManager.h"
#include "../../../Components/RenderComponent.h"
#include 
#include "../../../Engine/Texture2D.h"

dae::RenderManager::~RenderManager()
{
	std::cout << "Destroying render manager";
}

void dae::RenderManager::Initialize(int poolSize)
{
	//Create a pool of inactive renderComponents
	if(!m_IsInitialized)
		CreateNewRenderComponents(poolSize);
	m_IsInitialized = true;
}

//Render all the assigned render components
void dae::RenderManager::Render()
{
	if(m_NeedsSorting)
	{
		std::sort(m_pActiveRenderComponents.begin(), m_pActiveRenderComponents.end(),
		[](const std::shared_ptr& obj1, const std::shared_ptr& obj2)
		{
			return obj1->GetDepth() < obj2->GetDepth();
		});
	}

	for (unsigned int i = 0; i < m_pActiveRenderComponents.size(); ++i)
	{
		m_pActiveRenderComponents.at(i)->Render();
	}
}

std::shared_ptr dae::RenderManager::GetRenderComponent()
{
	//if there are no new rendercomponents left, create a couple more
	if (m_pInactiveRenderComponents.size() == 0)
		CreateNewRenderComponents(int(m_pActiveRenderComponents.size()));

	//get the last element in the vector
	auto toReturn = m_pInactiveRenderComponents.at(m_pInactiveRenderComponents.size() - 1);
	//delete the component from the vector
	m_pInactiveRenderComponents.pop_back();
	//push the component onto the active vector
	m_pActiveRenderComponents.push_back(toReturn);
	//return the component to the gameObject;
	return toReturn;
}

void dae::RenderManager::ReturnRenderComponent(std::shared_ptr pRenderComponent)
{
	//add the component to the inactive component list
	m_pInactiveRenderComponents.push_back(pRenderComponent);

	//find the component in the active list and remove it from the active list
	auto toRemove = std::find(m_pActiveRenderComponents.begin(), m_pActiveRenderComponents.end(), pRenderComponent);

	//remove the component from the active list
	if (toRemove != m_pActiveRenderComponents.end())
		m_pActiveRenderComponents.erase(std::remove(m_pActiveRenderComponents.begin(), m_pActiveRenderComponents.end(), pRenderComponent), m_pActiveRenderComponents.end());
	else
		std::cout << "WARNING: tried to return a render component that was not created by the rendermanager!!!\n";
}

void dae::RenderManager::SetNeedSorting()
{
	m_NeedsSorting = true;
}

void dae::RenderManager::CreateNewRenderComponents(int amount)
{
	for (int i = 0; i < amount; ++i)
	{
		std::shared_ptr temp(new RenderComponent());
		m_pInactiveRenderComponents.push_back(temp);
	}
}