#ifndef QUEUE_H
#define QUEUE_H

/*
 * @(#)Queue.h
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 1999-2003 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 */

#include <pthread.h>
#include <unistd.h>

/**
 * Implementation of a queue to reserve resources.
 *
 * @version 20030705
 * @author Jörg P. M. Haeger
 */
class Queue {
	pthread_mutex_t mutex;
	int *items;
	int n, maxItemsNum;
public:
	Queue() {
		pthread_mutex_init(&mutex, NULL);
		maxItemsNum = 1000;
		items = new int[maxItemsNum];
		n = 0;
	}

	virtual void add(int ID) {
		pthread_mutex_lock(&mutex);
		if (n == maxItemsNum) {
			pthread_mutex_unlock(&mutex);
			throw new Exception("too many users at the same time");
		}
		items[n++] = ID;
		pthread_mutex_unlock(&mutex);
	}

	virtual int getRank(int ID) {
		int i;
		pthread_mutex_lock(&mutex);
		for (i = 0; i < n && items[i] != ID; i++);
		pthread_mutex_unlock(&mutex);
		if (i < n)
			return i;
		else
			return 1000;
	}

	virtual void remove(int ID) {
		pthread_mutex_lock(&mutex);
		int i;
		for (i = 0; i < n && items[i] != ID; i++);
		for (; i < n - 1; i++)
			items[i] = items[i + 1];
		if (i < n)
			n--;
		pthread_mutex_unlock(&mutex);
	}
};

#endif
