package fr.upem.net.tcp.nonblocking;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Random;
import java.util.Scanner;

public class ClientTCPSum {
    private final SocketChannel socket;
    private final Random random = new Random(123456789); 

    public ClientTCPSum(String remoteHost, int remotePort) throws UnknownHostException, IOException {
        socket = SocketChannel.open();
        socket.connect(new InetSocketAddress(remoteHost, remotePort));
    }

    public void launch() throws IOException, InterruptedException {
        ByteBuffer bb = ByteBuffer.allocate(Integer.BYTES);
        try (Scanner sc = new Scanner(System.in)){
            while(sc.hasNextInt()) {
                for(int i=0 ; i<2 ; i++)  {
                    int op = sc.nextInt();
                    bb.putInt(op);
                    bb.flip();
                    int pos = random.nextInt(Integer.BYTES);
                    bb.limit(pos);
                    socket.write(bb);
                    Thread.sleep(1000);
                    bb.limit(Integer.BYTES);
                    socket.write(bb);
                    bb.clear();
                }
                bb.limit(Integer.BYTES);
                if(!readFully(bb,socket)) {
                    System.out.println("Serveur closed the connection before sending 4 bytes");
                    return;
                }
                bb.flip();
                int res = bb.getInt();
                System.out.println("result = " + res);
                bb.clear();
            }
        } finally {
            silentlyClose(socket);
        }
    }

    private static void silentlyClose(SocketChannel sc) {
        if (sc==null)
            return;
        try {
            sc.close();
        } catch (IOException e) {
            // silently ignore
        }
    }

    private static boolean readFully(ByteBuffer bb, SocketChannel sc) throws IOException {
        while(bb.hasRemaining())
            if(sc.read(bb)==-1) 
                return false;
        return true;    
    }

    private final static void usage() {
        System.out.println("ClientTCPSum <server> <port>");
    }
    
    public static void main(String[] args) throws NumberFormatException, UnknownHostException, IOException, InterruptedException {
        if(args.length != 2) {
            usage();
            return;
        }
        new ClientTCPSum(args[0],Integer.parseInt(args[1])).launch();
    }
}
