package client;

import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
import common.ClientInterface;
import common.ServerInterface;

public class Client extends UnicastRemoteObject implements ClientInterface {
    private String clientId;
    private ServerInterface server;

    protected Client(String clientId, ServerInterface server) throws RemoteException {
        super();
        this.clientId = clientId;
        this.server = server;
        server.registerClient(clientId, this);
    }

    public void sendMessage(String toId, String message) throws RemoteException {
        server.sendMessage(clientId, toId, message);
    }

    public void blockClient(String blockedId) throws RemoteException {
        server.blockClient(clientId, blockedId);
    }

    @Override
    public void receiveMessage(String fromId, String message) throws RemoteException {
        System.out.println("[" + fromId + "]: " + message);
    }

    // entry point
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            // get client ID and server info
            System.out.print("Enter your client ID: ");
            String clientId = scanner.nextLine();

            // get recipient ID
            System.out.print("Enter recipient ID: ");
            String toId = scanner.nextLine();

            Registry registry = LocateRegistry.getRegistry("localhost", 1099);
            ServerInterface server = (ServerInterface) registry.lookup("ChatServer");

            Client client = new Client(clientId, server);

            System.out.print("You can start chatting now. Type your messages below: Type exit to log out\n");

            while (true) {
                String msg = scanner.nextLine();
                if (msg.equalsIgnoreCase("exit")) {
                    System.out.println("Logging out...");
                    break;
                }
                client.sendMessage(toId, msg);
            }
        } catch (Exception e) {
            System.err.println("Client exception: " + e.getMessage());
        }
    }

}
