import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class SmallWriteDemo {
    public static void main(String[] args) throws Exception {
        if (args.length < 3) throw new IllegalArgumentException(
                "server <port> <rounds> | client <host> <port> <rounds> <combined|split|buffered> <true|false> <gap-ms>");
        if (args[0].equals("server")) {
            int rounds = rounds(args[2]);
            try (ServerSocket listener = new ServerSocket()) {
                listener.bind(new InetSocketAddress("127.0.0.1", Integer.parseInt(args[1])));
                listener.setSoTimeout(15_000);
                System.out.println("listening=" + listener.getLocalSocketAddress());
                try (Socket socket = listener.accept()) {
                    socket.setSoTimeout(5000);
                    DataInputStream input = new DataInputStream(socket.getInputStream());
                    for (int index = 0; index < rounds; index++) {
                        if (input.readInt() != 64) throw new IllegalStateException("length mismatch");
                        byte[] body = new byte[64];
                        input.readFully(body);
                        for (byte value : body) {
                            if (value != (byte) index) throw new IllegalStateException("body mismatch");
                        }
                        socket.getOutputStream().write(1);
                    }
                    if (input.read() != -1) throw new IllegalStateException("expected EOF");
                    System.out.println("validated rounds=" + rounds);
                }
            }
        } else if (args[0].equals("client")) {
            if (args.length != 7) throw new IllegalArgumentException("invalid client arguments");
            int rounds = rounds(args[3]);
            String mode = args[4];
            if (!mode.equals("combined") && !mode.equals("split") && !mode.equals("buffered")) {
                throw new IllegalArgumentException("invalid mode");
            }
            if (!args[5].equals("true") && !args[5].equals("false")) throw new IllegalArgumentException("invalid nodelay");
            int gapMillis = Integer.parseInt(args[6]);
            if (gapMillis < 0 || gapMillis > 100) throw new IllegalArgumentException("invalid gap");
            try (Socket socket = new Socket()) {
                socket.connect(new InetSocketAddress(args[1], Integer.parseInt(args[2])), 2000);
                socket.setSoTimeout(5000);
                socket.setTcpNoDelay(Boolean.parseBoolean(args[5]));
                OutputStream output = mode.equals("buffered")
                        ? new BufferedOutputStream(socket.getOutputStream(), 1024) : socket.getOutputStream();
                long[] elapsed = new long[rounds];
                long[] firstWrite = new long[rounds];
                long[] secondWrite = new long[rounds];
                long[] flushDone = new long[rounds];
                long origin = System.nanoTime();
                for (int index = 0; index < rounds; index++) {
                    byte[] body = new byte[64];
                    Arrays.fill(body, (byte) index);
                    byte[] header = ByteBuffer.allocate(4).putInt(body.length).array();
                    long started = System.nanoTime();
                    if (mode.equals("combined")) {
                        output.write(ByteBuffer.allocate(68).put(header).put(body).array());
                        firstWrite[index] = secondWrite[index] = System.nanoTime() - origin;
                    } else {
                        output.write(header);
                        firstWrite[index] = System.nanoTime() - origin;
                        Thread.sleep(gapMillis);
                        output.write(body);
                        secondWrite[index] = System.nanoTime() - origin;
                    }
                    output.flush();
                    flushDone[index] = System.nanoTime() - origin;
                    if (socket.getInputStream().read() != 1) throw new IllegalStateException("missing receipt");
                    elapsed[index] = System.nanoTime() - started;
                }
                socket.shutdownOutput();
                if (socket.getInputStream().read() != -1) throw new IllegalStateException("expected EOF");
                System.out.println("mode=" + mode + " nodelay=" + socket.getTcpNoDelay() + " gapMs=" + gapMillis);
                System.out.println("round,firstWriteReturnUs,secondWriteReturnUs,flushReturnUs,receiptElapsedUs");
                for (int index = 0; index < rounds; index++) {
                    System.out.println(index + "," + firstWrite[index] / 1000 + "," + secondWrite[index] / 1000
                            + "," + flushDone[index] / 1000 + "," + elapsed[index] / 1000);
                }
                Arrays.sort(elapsed);
                System.out.println("p50Us=" + elapsed[(int) Math.ceil(rounds * 0.50) - 1] / 1000
                        + " p95Us=" + elapsed[(int) Math.ceil(rounds * 0.95) - 1] / 1000 + " PASS");
            }
        } else throw new IllegalArgumentException("unknown mode");
    }

    private static int rounds(String value) {
        int rounds = Integer.parseInt(value);
        if (rounds < 1 || rounds > 100) throw new IllegalArgumentException("rounds outside 1..100");
        return rounds;
    }
}
