package proxy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.net.InetAddress;

public class ProxyServer {
    public static List<String> MSGs = new ArrayList<>();
    private static final int PORT = 1234;
    private static final int roundLength = 3600; //secs
    private ServerSocket server;
    private Forwarder f;

    public static void main(String[] args) throws IOException, InterruptedException {
        //start a thread for a forwarder
        ProxyServer ps = new ProxyServer();
        ps.run();
    }

    public ProxyServer() throws IOException, InterruptedException {
        server = new ServerSocket(PORT, 1, InetAddress.getLocalHost());
        f = new Forwarder(InetAddress.getByName("tcpserver.com"), 2345);
        System.out.println("\r\nRunning Server: " + "Host=" + server.getInetAddress().getHostAddress() + " Port=" + server.getLocalPort() + " Hostname=" + server.getInetAddress().getHostName());
    }

    void run() throws IOException {
        //Thread t = new Thread(() -> {
        //    try {
        //        Forwarder f = new Forwarder(InetAddress.getByName("tcpserver.com"), 2345);
        //        while (true) {
        //            f.forward();
        //            Thread.sleep(1000);
        //        }
        //    } catch (Exception e) {
        //        e.printStackTrace();
        //    }
        //});
        //t.start();
        ExecutorService executor = Executors.newCachedThreadPool();
        while (true) {
            //this will block until a connection is made
            Socket client = this.server.accept();
            executor.execute(new ServerThread(client));
        }
    }

    private class ServerThread implements Runnable {
        private Socket client;

        public ServerThread(Socket client) {
            this.client = client;
            System.out.println("New connection from " + client.getInetAddress().getHostAddress());
        }

        @Override
        public void run() {
            try {
                listen();
                this.client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        void listen() throws IOException {
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            String data = null;
            while((data = in.readLine()) != null) {
                //MSGs.add(data);
                f.forwardDirectly(data);
                System.out.println(client.getInetAddress().getHostAddress() + ": " + data);
            }
        }
    }
}
