// FileLogCache.cpp: implementation of the FileLogCache class.
//
//////////////////////////////////////////////////////////////////////

#include "FileLogCache.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

/* Create a new FileLogCache.  After a FileLogCache has been constructed,
 * not much else needs to be done to it. */
FileLogCache::FileLogCache(StrBuf filepath)
{
	changes = new ChangeSorter();
	main = new FileHead(filepath, this); //Create the "main" FileHead.
	from = NULL;
	into = NULL;
	main->scanMain(); //check all revs in "main"
}

FileHead* FileLogCache::AddFrom(StrBuf filepath)
{
	if (from == NULL) //If we don't have any "from" FileHeads yet:
	{
		from = new FileHead(filepath, this);
		return from;
	} //otherwise:
	FileHead* working = new FileHead(filepath, this);
	working->next = from;
	from = working;
	return from;
}

/*AddInto works much like AddFrom - I don't think it needs explanation. */
FileHead* FileLogCache::AddInto(StrBuf filepath)
{
	if (into == NULL)
	{
		into = new FileHead(filepath, this);
		return into;
	}
	FileHead* working = new FileHead(filepath, this);
	working->next = into;
	into = working;
	return into;
}

FileHead* FileLogCache::AddAfter(StrBuf filepath, FileHead* caller)
{
	if (caller == main) return AddFrom(filepath);
	FileHead* working = new FileHead(filepath, this);
	working->next = caller->next;
	caller->next = working;
	return working;
}


FileHead* FileLogCache::Get(StrBuf filepath, bool exfrom, FileHead* caller)
{
	if (main->file == filepath){ //Was it main?
		return main;
	}
	FileHead* working = from; //Is it in from?
	while (working != NULL)
	{
		if (working->file == filepath) return working;
		working = working->next;
	}
	working = into; //Is it in into?
	while (working != NULL)
	{
		if (working->file == filepath) return working;
		working = working->next;
	}
	/* Make a new one, then. */
	if (caller == main) //If the caller was "main"...
	{
		if (exfrom) return AddFrom(filepath);
		else return AddInto(filepath);
	}
	else
	{
		return AddAfter(filepath, caller);
	}
}

FileLogCache::~FileLogCache() //Clean up everything when deleting this object.
{
	if (main != NULL) delete main;
	if (from != NULL) delete from;
	if (into != NULL) delete into;
	delete changes;
}
