package it.polimi.ingsw.gc14.Network.RMI.Client;

import it.polimi.ingsw.gc14.Controller.ClientController;
import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.RMI.Common.IClientCallback;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;


/**
 * RMI client callback implementation of {@link IClientCallback}.
 * Receives notifications from the server and updates the client game model.
 */
public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCallback {

    /** The client controller used to apply events and update the model */
    private final ClientController clientController;


    /**
     * Class constructor.
     * @param clientController the client controller
     * @throws RemoteException if any RMI error occurs
     */
    public ClientCallbackImpl(ClientController clientController) throws RemoteException {
        this.clientController = clientController;
    }


    /**
     * Called by the server when the game is initialized.
     * Sets the client game model in the {@link ClientController}.
     * @param model the initialized {@link Game} model
     * @throws RemoteException if any RMI error occurs
     */
    @Override
    public void onGameInit(Game model) throws RemoteException {
        clientController.setModel(model);
    }


    /**
     * Called by the server when an action has been accepted.
     * If the event contains an error, it is printed to the console.
     * Otherwise, the event is applied to the local model.
     * @param event the {@link NetworkEvent} sent by the server
     * @throws RemoteException if any RMI error occurs
     */
    @Override
    public void onAction(NetworkEvent event) throws RemoteException {
        if(event.getIsError()) {
            System.out.println(event.toString());
        } else {
            event.apply(clientController.localController);
            //clientController.view.update();           TODO
        }
    }
}
