//
// Tools_ResourceExportLog.cpp
//
// Created by Richard Rice - 30/05/2008
// 
// Copyright (C) 2008 Rebellion, All Rights Reserved.
//

#include "Core/Asura.h"
#include "Load&Save/Tools_ResourceExportLog.h"

#include "Debugging/Asura_Logfile.h"

struct Tools_ResourceExportLogEntry
{
	const char* m_szType;
	const char* m_szName;
};


Asura_String Tools_ResourceExportLog::s_xLogName;
int Tools_ResourceExportLog::s_iStackDepth;
int Tools_ResourceExportLog::s_iHighestLoggedEntry;
Tools_ResourceExportLogEntry Tools_ResourceExportLog::s_axStack[TOOLS_RESOURCEXPORTLOG_STACKSIZE];



void Tools_ResourceExportLog::OpenLog(const char* szFilename)
{
	Asura_Assert(s_xLogName.IsBlank(), "Previous log file not closed?");
	s_xLogName = szFilename;

	//make sure the file is empty
	Asura_SimpleLogfileClear(szFilename);

	//reset the stack
	s_iStackDepth = 0;
	s_iHighestLoggedEntry = -1;
}

void Tools_ResourceExportLog::CloseLog()
{
	Asura_Assert(s_iStackDepth==0,"Expecting everything to have been removed from stack before closing the logfile");
	s_xLogName.MakeNull();
}

void Tools_ResourceExportLog::ResetLog()
{
	if(!s_xLogName.IsBlank())
	{
		Asura_SimpleLogfileClear(s_xLogName.GetString());
	}
}

void Tools_ResourceExportLog::AddToStack(const char* szType, const char* szName, bool bLogNow)
{
	if(!IsOpen()) return;
	
	Asura_Assert(s_iStackDepth<TOOLS_RESOURCEXPORTLOG_STACKSIZE, "Too many entries in stack for Tools_ResourceExportLog"); 
	if(s_iStackDepth<TOOLS_RESOURCEXPORTLOG_STACKSIZE)
	{
		s_axStack[s_iStackDepth].m_szType = szType;
		s_axStack[s_iStackDepth].m_szName = szName;
	}
	s_iStackDepth++;

	if(bLogNow)
	{
		ForceOutputToLog();
	}
}

void Tools_ResourceExportLog::ForceOutputToLog()
{
	if(!IsOpen()) return;

	char acBuffer[1024];
	//write out everything in stack that has yet to be done
	for(int i=s_iHighestLoggedEntry+1; i<s_iStackDepth && i<TOOLS_RESOURCEXPORTLOG_STACKSIZE; i++)
	{
		char* pcPos = acBuffer;
		int iSpaceLeft = sizeof(acBuffer);
		//insert indentation
		for(int j=0;j<i;j++)
		{
			*pcPos++ = ' ';
			*pcPos++ = ' ';
			iSpaceLeft-= 2;
		}
		*pcPos = 0;

		//add the type
		if(s_axStack[i].m_szType && *s_axStack[i].m_szType)
		{
			Asura_PrintfToBfr(pcPos,"%s : ",iSpaceLeft,true,s_axStack[i].m_szType);
			pcPos += strlen(pcPos);
		}
		//add the resource name
		if(s_axStack[i].m_szName && *s_axStack[i].m_szName)
		{
			Asura_PrintfToBfr(pcPos,"%s",iSpaceLeft,true,s_axStack[i].m_szName);
			pcPos += strlen(pcPos);
		}

		//output to the logfile
		Asura_SimpleLogfileOutput((s_xLogName.GetString(),"%s\n", acBuffer));
		
	}
	s_iHighestLoggedEntry = s_iStackDepth-1;
}

void Tools_ResourceExportLog::RemoveFromStack()
{
	if(!IsOpen()) return;

	Asura_Assert(s_iStackDepth>0, "Nothing left in stack to remove");
	if(s_iStackDepth>0)
	{
		s_iStackDepth--;
		if(s_iHighestLoggedEntry>=s_iStackDepth)
		{
			s_iHighestLoggedEntry = s_iStackDepth-1;
		}
	}
}