package proxy;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class Forwarder {
    private Socket socket = null;
    public static boolean forwarderReady = false;
    private PrintWriter out;

    protected Forwarder(InetAddress serverAddress, int serverPort) throws IOException, InterruptedException {
        try {
            bindSocket(serverAddress, serverPort);
        } catch (Exception e) {
            System.out.println("Retrying...");
            Thread.sleep(5000);
            bindSocket(serverAddress, serverPort);
        }
    }

    private void bindSocket(InetAddress serverAddress, int serverPort) throws IOException {
        this.socket = new Socket(serverAddress, serverPort);
        while(!socket.isBound()) ;
        forwarderReady = true;
        out = new PrintWriter(this.socket.getOutputStream(), true);
        System.out.println("Connected to " + serverAddress.getHostAddress() + ":" + serverPort);
    }

    protected void forward() {
        System.out.println("Round ends. Forwarding...");
        StringBuilder messages = new StringBuilder();
        synchronized (ProxyServer.MSGs) {
            if(ProxyServer.MSGs.isEmpty())
                return;
            while (!ProxyServer.MSGs.isEmpty()) {
                out.write(ProxyServer.MSGs.remove(0) +"\n");
                out.flush();
            }
        }

        //System.out.println("Active closing");
        //this.socket.close();
    }

    protected void forwardDirectly(String data) {
        out.write(data+"\n");
        out.flush();

        //System.out.println("Active closing");
        //this.socket.close();
    }

}
