package cap16.borsa;

import java.net.*;
import java.rmi.*;
import java.rmi.server.*;

public class BorsaImpl extends UnicastRemoteObject
  implements Borsa
{ private static int MAX_TITOLI = 10;
  private Titolo[] tit;
  private int numTitoli;
  public BorsaImpl() throws RemoteException
  { tit = new Titolo[MAX_TITOLI];
  }
  public synchronized boolean registra(
    String nomeTitolo, double soglia, Notifica n)
    throws BorsaException, RemoteException
  { for (int i = 0; i < numTitoli; i++)
    { if (tit[i].getNome().equals(nomeTitolo))
        return tit[i].setCliente(n, soglia);
    }
    throw new BorsaException();
  }
  public synchronized void setValore(String t, double v)
    throws BorsaException, RemoteException
  { for (int i = 0; i < numTitoli; i++)
    { if (tit[i].getNome().equals(t))
      { tit[i].setValore(v);
        return;
      }
    }
    throw new BorsaException();
  }
  public synchronized double getValore(String t)
    throws BorsaException, RemoteException
  { for (int i = 0; i < numTitoli; i++)
      if (tit[i].getNome().equals(t))
        return tit[i].getValore();
    throw new BorsaException();
  }
  public synchronized boolean aggiungiTitolo(
    String nome, double valoreIniziale)
  { if (numTitoli < MAX_TITOLI)
    { tit[numTitoli] = new Titolo(nome, valoreIniziale);
      numTitoli++;
      return true;
    }
    return false;
  }
  public static void main(String[] args)
  { try
    { BorsaImpl bi = new BorsaImpl();
      bi.aggiungiTitolo("Superplastic", 44.0);
      bi.aggiungiTitolo("MacroSoft", 31.5);
      bi.aggiungiTitolo("MoonMicrosystems", 39.7);
      Naming.rebind("//localhost/borsa", bi);
    }
    catch (RemoteException re)
    { System.err.println("Errore di rete");
    }
    catch (MalformedURLException mue)
    { System.err.println("URL errato");
    }
  }
  class Titolo
  { private String nome;
    private double valore;
    private Notifica cliente;
    private double soglia;
    Titolo(String n, double v)
    { nome = n;
      valore = v;
    }
    double getValore()
    { return valore;
    }
    void setValore(double v)
    { valore = v;
      if ((cliente != null) && (v >= soglia))
        try
        { cliente.notifica(nome, v);
        }
        catch (RemoteException re)
        { cliente = null;
        }
    }
    String getNome()
    { return nome;
    }
    boolean setCliente(Notifica n, double s)
    { if (cliente == null)
      { cliente = n;
        soglia = s;
        return true;
      }
      return false;
    }
  }
}
