package de.hsadmin.core.qserv;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import de.hsadmin.core.model.Transaction;

public class WaitingTasksProcessor extends AbstractProcessor {

	private static final long serialVersionUID = 1198528557513957546L;
	
	private Processor main;
	private List<WaitingProcessor> waitingTasks;

	public WaitingTasksProcessor(Processor mainProcessor) {
		this.main = mainProcessor;
		this.waitingTasks = new ArrayList<WaitingProcessor>();
	}
	
	@Override
	public Object process() throws ProcessorException {
		return main.process();
	}
	
	@Override
	public void finalize(Transaction transaction, QueueTask task)
			throws ProcessorException {
		if (task.getException() == null) {
			for (WaitingProcessor p : waitingTasks) {
				QueueTask wTask = 
					new QueueTask(task.getUser(), task.getTitle() + " / " + p.getTitle(), task.getTitle() + " / " + p.getTitle(), p.getProc());
				transaction.getEntityManager().persist(wTask);
				transaction.enqueue(p.getHost(), wTask);
			}
		}
		super.finalize(transaction, task);
	}

	public void appendProcessor(String hostName, Processor waitingTask, String title) {
		waitingTasks.add(new WaitingProcessor(hostName, waitingTask, title));
	}

	class WaitingProcessor implements Serializable {
		private static final long serialVersionUID = -5205925170344385765L;
		private String host;
		private Processor proc;
		private String title;
		public WaitingProcessor(String hostName, Processor processor, String procTitle) {
			host = hostName;
			proc = processor;
			title = procTitle;
		}
		public Processor getProc() {
			return proc;
		}
		public String getHost() {
			return host;
		}
		public String getTitle() {
			return title;
		}
	}
}
