package it.polimi.ingsw.gc14.Network.RMI.Client;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import it.polimi.ingsw.gc14.Controller.ClientController;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.RMI.Common.IGameServer;

public class RMIClient  {

    private final String host;
    private final int port;
    private IGameServer stub;

    public RMIClient(String host, int port) {
        this.host = host;
        this.port = port;
    }


    public boolean connect(String username,int preferredInt,ClientController clientController) {
        // 1. Connettiti al registry
        try {
            Registry registry = LocateRegistry.getRegistry(host, port);

            // 2. Prendi lo stub del server
            this.stub = (IGameServer) registry.lookup("RMIGameServer");

            // 3. Crea il callback e registralo
            ClientCallbackImpl callback = new ClientCallbackImpl(clientController);

            if (!stub.joinGame(username,preferredInt, callback))
            {
                stub = null;
                return false;
            }
            else
            {
                return true;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    public void doEvent(NetworkEvent event) throws Exception {
        stub.doEvent(event);
    }

}