package org.academiadecodigo.enuminatti.inetaddress;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class UDPClient {
    public static void main(String[] args) {

        String[] hostAndPort = getString("Host:port").split(":");
        if (hostAndPort.length != 2)
            throw new IllegalArgumentException();

        InetSocketAddress socketAddress = new InetSocketAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1]));

        byte[] recvBuffer = new byte[1024];

        String message = getString("Message to uppercase");
        DatagramSocket udpSocket = null;

        try {
            udpSocket = new DatagramSocket();

            while (!message.equals("/quit")) {

                byte[] messageBytes = message.getBytes();

                DatagramPacket sendPacket = new DatagramPacket(messageBytes, messageBytes.length, socketAddress);
                udpSocket.send(sendPacket);

                DatagramPacket recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length, udpSocket.getLocalSocketAddress());
                udpSocket.receive(recvPacket);

                String recvString = new String(recvBuffer, 0, recvPacket.getLength());
                System.out.println("reply from server: " + recvString);

                message = getString("Message to uppercase");
            }


        } catch (SocketException e) {
            System.out.println("Couldn't open socket.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (udpSocket != null) {
                byte[] messageBytes = message.getBytes();

                DatagramPacket sendPacket = new DatagramPacket(messageBytes, messageBytes.length, socketAddress);
                try {
                    udpSocket.send(sendPacket);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                udpSocket.close();
            }
        }
    }

    private static String getString(String name) {
        System.out.printf(name + ": ");

        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }

}
