// internal record locking stuff
#include "ctdl.h"
#pragma hdrstop

#include "room.h"
#include "roompriv.h"
#include "lock.h"

typedef enum
	{
	LT_ROOM,	LT_HALL,	LT_USER,	LT_MSG
	} ltypes;

typedef struct locks
	{
	struct locks *next;
	ltypes lockType;
	long lockNum;
	uint key;
	} locks;

static Key lastKey; 		/* last key used - ++ for next	*/
locks *recLocks;			/* locked records and keys		*/

static locks *AddLock(void)
	{
	locks *l;

	l = (locks *) addLL((void **) &recLocks, sizeof(*l));

	if (l)
		{
		if (!++lastKey)
			{
			lastKey++;
			}

		l->key = lastKey;
		return (l);
		}
	else
		{
		mPrintf(getmsg(188), getmsg(1362));
		return (NULL);
		}
	}

Key lockRoom(r_slot room)
	{
	locks *l;

	if (getRoomTab(room)->locked)
		{
		return (0);
		}

	l = AddLock();

	if (l)
		{
		l->lockType = LT_ROOM;
		l->lockNum = room;
		getRoomTab(room)->locked = TRUE;

		return (l->key);
		}
	else
		{
		return (0);
		}
	}

Bool unlockRoom(r_slot room, Key key)
	{
	if (!getRoomTab(room)->locked)
		{
		return (TRUE);
		}

	locks *l;
	long i;
	for (i = 1, l = recLocks; l; i++, l = (locks *) getNextLL(l))
		{
		if (l->lockType == LT_ROOM && l->lockNum == room && l->key == key)
			{
			deleteLLNode((void **) &recLocks, i);
			getRoomTab(room)->locked = FALSE;
			return (TRUE);
			}
		}

	return (FALSE);
	}
