import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class EchoClient {

    private Socket socket;
    private boolean running = true;

    public EchoClient(Socket socket){
        this.socket = socket;
    }

    public void sendToServer(String message) throws IOException {
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        outputStream.writeUTF(message);
    }

    public void stop(){
        running = false;
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Verbindung zum Server wurde beendet.");
    }

    public boolean isRunning(){
        return running;
    }

    public String promptForNewMessage(){
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Nachricht an den Server senden (\\exit zum Beenden): ");
            return scanner.nextLine();
        }
    }

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 1234);
        try {
            EchoClient client = new EchoClient(socket);
            final Object lock = new Object(); // Gemeinsamer Lock für Synchronisation
            Receiver receiver = new Receiver(socket, lock);
            receiver.start();

            while (client.isRunning()) {
                String message = client.promptForNewMessage();
                client.sendToServer(message);
                Thread.sleep(50);
                if (message.equals("\\exit")) {
                    client.stop();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
