package fr.univ.lyon1.gui.handlers;

import fr.univ.lyon1.common.ServerConfiguration;
import fr.univ.lyon1.gui.ClientGUI;
import fr.univ.lyon1.gui.ClientPanel;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;

public class MainHandler implements Handler {
    private ClientPanel clientPanel;
    @Nullable
    private ClientGUI client;

    @Override
    public void launch(Stage stage) throws IOException {
        System.out.println("New...");
        @NotNull
        final ServerConfiguration serverConfiguration = ServerConfiguration.load();
        System.out.println("Launch Client GUI...");
        this.client = new ClientGUI(this, serverConfiguration.getAddress(), serverConfiguration.getPort());

        System.out.println("Set...");
        stage.setTitle("Chat client");
        stage.setWidth(440);

        System.out.println("Set panel...");
        this.clientPanel = new ClientPanel(this);
        Group root = new Group();
        root.getChildren().add(this.clientPanel);
        Scene scene = new Scene(root, 600, 500);

        System.out.println("Set scene...");
        stage.setScene(scene);
        stage.show();

        if (this.client != null) {
            System.out.println("Run...");
            this.client.run();
        }
    }

    public void sendMessage(String msg) {
        if (client != null) {
            client.sendMessage(msg);
        }
    }

    public void receiveMessage(String msg) {
        clientPanel.addMessage(msg);
    }
}