package at.ac.tuwien.sbc.valesriegler.group;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.ac.tuwien.sbc.valesriegler.common.HasId;
import at.ac.tuwien.sbc.valesriegler.common.Util;
import at.ac.tuwien.sbc.valesriegler.group.actions.DeliveryOrderRequest;
import at.ac.tuwien.sbc.valesriegler.group.jms.JMSGroupConnector;
import at.ac.tuwien.sbc.valesriegler.types.DeliveryGroupData;
import at.ac.tuwien.sbc.valesriegler.types.DeliveryStatus;

public class DeliveryGroup implements Runnable, HasId {
	private static final Logger log = LoggerFactory.getLogger(DeliveryGroup.class);
	private static int idNext = 0;

	private DeliveryGroupData deliveryGroupData;

	public DeliveryGroup() {
		deliveryGroupData = new DeliveryGroupData(++idNext);
	}

	public DeliveryGroup(int id) {
		deliveryGroupData = new DeliveryGroupData(id);
	}

	public DeliveryGroupData getDeliveryGroupData() {
		return deliveryGroupData;
	}

	@Override
	public int getId() {
		return deliveryGroupData.getId();
	}

	public void setDeliveryGroupData(DeliveryGroupData deliveryGroupData) {
		this.deliveryGroupData = deliveryGroupData;
	}

	@Override
	public void run() {
		log.debug("Thread started for:" + this);
		try {
			if (!Util.runSimulation) {
				Thread.sleep((long) (Math.random() * 10000));
			}
			switch (deliveryGroupData.getDeliveryStatus()) {
				case START : // should not happen.
					break;
				case ORDER_PENDING :
					getDeliveryGroupData().getOrder().genId();
					JMSGroupConnector conn = JMSGroupConnector.getConnector(deliveryGroupData.getPizzeriaId());
					conn.send(new DeliveryOrderRequest(deliveryGroupData));
					break;
				case IN_PROGRESS : // do nothing
					break;
				case DELIVERED : // do nothing
					break;
				case PAID : // do nothing
					break;
				case IS_DELIVERED : // do nothing
					break;
				case DELIVERY_FAILED : // do nothing
					break;
				default : // do nothing
					break;
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	// lets order at the pizzaria.
	public void orderSomeFood() {
		log.debug("orderSomeFood(): " + this);
		deliveryGroupData.setDeliveryStatus(DeliveryStatus.ORDER_PENDING);
		GroupAgent.getInstance().getGroupModel().fireTableDataChanged();
		new Thread(this).start();
	}
}
