/*	Renegade Scripts.dll
	Resource loader class
	Copyright 2007 Jonathan Wilson, Mark Sararu

	This file is part of the Renegade scripts.dll
	The Renegade scripts.dll is free software; you can redistribute it and/or modify it under
	the terms of the GNU General Public License as published by the Free
	Software Foundation; either version 2, or (at your option) any later
	version. See the file COPYING for more details.
	In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence.
	Only the source code to the module(s) containing the licenced code has to be released.
*/
#define RESOURCEMANGER_USETHREAD
class ResourceLoadTask
{
protected:
	virtual void LoadResource();
	void *Data;
public:
	ResourceLoadTask();
	ResourceLoadTask(void *data);
	bool RunResourceLoadTask(void* arg);
};


struct LoadTaskListNode
{
	LoadTaskListNode()
	{
		Next = NULL;
		Prev = NULL;
		Data = NULL;
	}
	LoadTaskListNode(ResourceLoadTask *data)
	{
		Next = NULL;
		Prev = NULL;
		Data = data;
	}
	LoadTaskListNode* Next;
	LoadTaskListNode* Prev;
	ResourceLoadTask* Data;
};

class LoadTaskList
{
public:
	LoadTaskList()
	{
		Head = NULL;
		Tail = NULL;
	}
	LoadTaskListNode* Head;
	LoadTaskListNode* Tail;
	void AppendNode(LoadTaskListNode* node)
	{
		if (Head == NULL)
		{
			Head = node;
			node->Prev = NULL;
		}
		else 
		{
			Tail->Next = node;
			node->Prev = Tail;
		}
		Tail = node;
		node->Next = NULL;
	}
	void PrependNode(LoadTaskListNode* node)
	{
		if (Head == NULL)
		{
			Head = node;
			node->Next = NULL;
		}
		else 
		{	
			Head->Prev = node;
			node->Next = Head;
		}
		Head = node;
		node->Prev = NULL;
	}
	void InsertNode(LoadTaskListNode* node, LoadTaskListNode* after)
	{
		node->Next = after->Next;
		node->Prev = after;
		if (after->Next != NULL)
		{
			after->Next->Prev = node;
		} 
		else 
		{
			Tail = node;
		}
		after->Next = node;
	}
	void RemoveNode(LoadTaskListNode* node)
	{
		if (node->Prev == NULL)
		{
			Head = node->Next;
		}
		else 
		{
			node->Prev->Next = node->Next;
		}
		if (node->Next == NULL)
		{
			Tail = node->Prev;
		}
		else 
		{
			node->Next->Prev = node->Prev;
		}
		node->Next = NULL;
		node->Prev = NULL;
	}
	void RemoveAllNodes()
	{
		while(Head != NULL)
		{
			RemoveNode(Head);
		}
	}
};

enum ResourceLoadPriority {
	RESOURCELOADPRIORITY_NORMAL = 0x0,
	RESOURCELOADPRIORITY_HIGH = 0x1,
};

class ResourceLoaderClass
{
protected:
#ifdef RESOURCEMANGER_USETHREAD
	LoadTaskList* LoadTasks;
	HANDLE Mutex;
	HANDLE TaskThreadHandle;
	unsigned int TaskThreadID;
	static unsigned int WINAPI ProcessTasks(void *data);
#endif
public:
	ResourceLoaderClass();
	~ResourceLoaderClass();
	void EnqueueTask(ResourceLoadTask *task, ResourceLoadPriority priority);
	void ProcessTaskImmediate(ResourceLoadTask *task);
#ifdef RESOURCEMANGER_USETHREAD
	void SetPriority(int priority);
#endif
};

extern ResourceLoaderClass *ResourceFactory;
