import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.util.Scanner;

public class Echoclient {
    public static void main(String[] args) {
        String host = "localhost";
        int port = 1234;
        String password = System.getenv("KEY_PASSWORD");

        try {
            // TrustStore laden
            KeyStore trustStore = KeyStore.getInstance("PKCS12");
            trustStore.load(new FileInputStream("truststore.jks"), password.toCharArray());

            // TrustManagerFactory initialisieren
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
            trustManagerFactory.init(trustStore);

            // SSLContext initialisieren
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            try (SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
                 DataInputStream input = new DataInputStream(sslSocket.getInputStream());
                 DataOutputStream output = new DataOutputStream(sslSocket.getOutputStream());
                 Scanner scanner = new Scanner(System.in)) {

                System.out.println("Verbunden mit Server. Geben Sie Text ein (exit zum Beenden):");

                String message;
                while (true) {
                    System.out.print("> ");
                    message = scanner.nextLine();
                    if ("exit".equalsIgnoreCase(message)) break;
                    output.writeUTF(message);
                    String response = input.readUTF();
                    System.out.println("Antwort vom Server: " + response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Client wird beendet");
    }
}