package org.academiadecodigo.enuminatti.inetaddress;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;

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

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

        int portNumber = Integer.parseInt(getPort());

        byte[] recvBuffer = new byte[1024];

        DatagramSocket udpSocket = null;
        String recvString;

        try {
            udpSocket = new DatagramSocket(portNumber);

            while (true) {

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

                recvString = new String(recvPacket.getData(), recvPacket.getOffset(), recvPacket.getLength());

                if (recvString.contains("/quit"))
                    break;

                System.out.println(recvPacket.getSocketAddress() + " < " + recvString);

                String instructions = "(send '/quit' to close)";

                String recvStringUpper = recvString.toUpperCase() + "\n" + instructions;

                byte[] uppercasedBytes = recvStringUpper.getBytes();

                DatagramPacket sendPacket = new DatagramPacket(uppercasedBytes, uppercasedBytes.length, recvPacket.getSocketAddress());
                udpSocket.send(sendPacket);

                System.out.println(recvPacket.getSocketAddress() + " > " + recvStringUpper);

            }

        } catch (SocketException e) {
            System.out.println("Couldn't open socket.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Closing server.");
            if (udpSocket != null)
                udpSocket.close();
        }
    }

    private static String getPort() {
        Scanner scanner = new Scanner(System.in);
        System.out.printf("Port: ");
        return scanner.nextLine();
    }
}
