package omq.server.remote.request;

import java.util.concurrent.BlockingQueue;

import omq.Remote;
import omq.common.message.request.Request;
import omq.common.util.Serializer;


import com.rabbitmq.client.QueueingConsumer.Delivery;

/**
 * 
 * @author Sergi Toda <sergi.toda@estudiants.urv.cat>
 * 
 */
public class InvocationThread extends Thread {
	private Remote obj;
	private BlockingQueue<Delivery> deliveryQueue;
	private boolean killed = false;

	public InvocationThread(Remote obj, BlockingQueue<Delivery> deliveryQueue) {
		this.obj = obj;
		this.deliveryQueue = deliveryQueue;
	}

	@Override
	public void run() {
		while (!killed) {
			try {
				// Get the delivery
				Delivery delivery = deliveryQueue.take();

				// Get the request
				Request req = (Request) Serializer.deserialize(delivery.getBody());

				// Invoke the method requested
				req.invokeRequest(obj, delivery.getProperties());
			} catch (InterruptedException i) {
				killed = true;
			} catch (Exception e) {
				System.out.println("Error a l'Invocation Thread \nException: " + e);
			}

		}
	}

	public Remote getObj() {
		return obj;
	}

	public void setObj(Remote obj) {
		this.obj = obj;
	}

	public BlockingQueue<Delivery> getDeliveryQueue() {
		return deliveryQueue;
	}

	public void setDeliveryQueue(BlockingQueue<Delivery> deliveryQueue) {
		this.deliveryQueue = deliveryQueue;
	}
}
