package ANTARCTICA.downloadTest;

import java.io.*;
import java.util.*;
import com.objectspace.voyager.*;

public class REMOTEMethod implements Method, IPieceListener {

	private IPick pick;
	private Object piece;

	public REMOTEMethod(IPick pick) {
		this.pick = pick;
	}

	public void retrieve(int piece) throws Exception {
		Factory.create("ANTARCTICA.downloadTest.MobileAgent",
			new Object[]{Proxy.of(this), pick, new Integer(piece)},
			((Proxy) pick).getURL());
		synchronized(this) {
			while (this.piece == null) {
				try {
					wait();
				} catch (Exception e) {
				}
			}
		}
		if (!(this.piece instanceof Piece)) {
			Exception exception = (Exception) this.piece;
			this.piece = null;
			throw exception;
		}
	}

	public boolean canDownload() {
		return (piece != null);
	}

	public void download(String dirname) throws IOException {
		((Piece) piece).download(dirname + "/" + ((Piece) piece).getName());
	}

	public void newPiece(Object thePiece) {
		synchronized(this) {
			piece = thePiece;
			notify();
		}
	}
}
