package ANTARCTICA.downloadTest;

import com.objectspace.voyager.*;
import com.objectspace.voyager.agent.*;
import com.objectspace.voyager.mobility.*;

public class MobileAgent implements IMobileAgent {

	private IPieceListener listener;
	private IPick pick;
	private int numPiece;
	private Piece piece;
	private Exception exception;

	public MobileAgent(IPieceListener listener,
			IPick pick, int piece) throws MobilityException {
		this.listener = listener;
		this.pick = pick;
		this.numPiece = piece;
		IAgent agent = Agent.of(this);
		agent.setAutonomous(true);
		agent.moveTo(((Proxy) pick).getURL(), "work");
	}

	public void preDeparture(String source, String destination)
			throws MobilityException {
		System.out.println("MobileAgent: Travelling to "+destination+"...");
	}

	public void preArrival() throws MobilityException {
		System.out.println("MobileAgent: Arriving...");
	}

	public void postArrival() {
		System.out.println("MobileAgent: Arrival completed");
	}

	public void postDeparture() {
		System.out.println("MobileAgent: Trip completed");
	}

	public void work() throws MobilityException {
		try {
			piece = (Piece) pick.pick(numPiece);
		} catch (Exception e) {
			exception = e;
		}
		IAgent agent = Agent.of(this);
		agent.moveTo(((Proxy) listener).getURL(), "done");
	}

	public void done() {
		if (exception == null) {
			listener.newPiece(piece);
		} else {
			listener.newPiece(exception);
		}
	}

}
