package astaRMI;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
 
public class Client implements ClientInterface {
 
	public void offer(int howMuch) throws RemoteException {
		System.out.println("The current offer is "+howMuch);
		return;
	}
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
 
		if(args.length==0) {
			System.out.println("Client name servername");
			return;
		}
 
//		if(System.getSecurityManager() == null) 
//			System.setSecurityManager(new RMISecurityManager());
 
		Client c = new Client();
		ClientInterface ci = null; 
		try {
			ci = ((ClientInterface) UnicastRemoteObject.exportObject(c));
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		InterfacciaBattitore ib = null; 
		try {
			ib = (InterfacciaBattitore) Naming.lookup("rmi://"+args[1]+"/battitore");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
		try {
			ib.register(args[0],(ClientInterface) ci);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		int offerta = 0;
		int current = 0; 
		do {
		try {
			offerta = (int) (Math.random() * 100.0);
			current = ib.offer(args[0],offerta);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		} while(current > offerta);
		// Adesso offri di piĆ¹ solo se lo dice l'utente. 
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		do {
			String line = null;
			try {
				line = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			int off = Integer.parseInt(line);
			try {
				ib.offer(args[0], off);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		} while(true);
 
	}
 
}