#ifndef WRITERQUEUES_H
#define WRITERQUEUES_H

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

#include "Queue.h"
#include "Server.h"

class WriterQueues: public Queue {
	private: pthread_mutex_t mutex;
	Queue *queues;
	int numOfQueues;
public:
	WriterQueues() {
		pthread_mutex_init(&mutex, NULL);
		numOfQueues = config.getNumOfWriters();
		queues = new Queue[numOfQueues];
		log.put(5, S.e + "numOfQueues = " + numOfQueues);
	}

	int add(int ID, String &medium, int speed = 1) {
		pthread_mutex_lock(&mutex);
		int count = 0;
		for (int i = 0; i < numOfQueues; i++)
			if (config.deviceSupports(i, medium, speed)) {
				queues[i].add(ID);
				count++;
			}
		pthread_mutex_unlock(&mutex);
		if (count == 0)
			throw new Exception(S.e
				+ "No " + speed + "x " + medium + " writer available!");
		return count;
	}

	int available(int ID, String &medium, int speed = 1) {
		pthread_mutex_lock(&mutex);
		int count = 0;
		for (int i = 0; i < numOfQueues; i++)
			if (config.deviceSupports(i, medium, speed))
				count++;
		pthread_mutex_unlock(&mutex);
		return count;
	}

	int getRank(int ID) {
		pthread_mutex_lock(&mutex);
		int min = 1000;
		for (int i = 0; i < numOfQueues; i++) {
			int rank = queues[i].getRank(ID);
			log.debug("WriterQueues", S.e + "getRank"
				+ " queue = " + i + " rank = " + rank);
			if (rank < min)
				min = rank;
		}
		pthread_mutex_unlock(&mutex);
		return min;
	}

	int getWriter(int ID) {
		pthread_mutex_lock(&mutex);
		int no = -1;
		for (int i = 0; i < numOfQueues; i++) {
			int rank = queues[i].getRank(ID);
			if (no < 0 && rank == 0)
				// this is our writer
				no = i;
			else
				// quit all other queues
				queues[i].remove(ID);
		}
		pthread_mutex_unlock(&mutex);
		return no;
	}

	void remove(int ID) {
		pthread_mutex_lock(&mutex);
		for (int i = 0; i < numOfQueues; i++)
			queues[i].remove(ID);
		pthread_mutex_unlock(&mutex);
	}
};

#endif
