/*
 * Implementation of a simple UDP Quote of the Day client.
 *
 * Usage:
 *      java quoteUDPClient [-h host] [-p port]
 * Optional arguments:
 *      -h host: UDP quote of day server IP or domain name.
 *      -p port: UDP quote of day port where server is listening.
 *
 * @author Francisco M. Delicado
 * @version 10/10/2019
 */

import javax.xml.crypto.Data;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.*;
import java.net.*;


import static java.lang.System.*;

public class quoteUDPClient {
    private static int port = 17; //Default quote of day UDP port
    private static InetAddress serveraddr;

//-----------------------------------------------

    /**
     * Function to parse the command line
     *
     * @param line (String[]) the command line parameters
     * @return a boolean value: true if command line is right, otherwise false
     */
    private static boolean ParseInput(String[] line) {
        String host = "localhost"; //Default quote of day server
        String arg;
        for (int i = 0; i < line.length; i++) {
            arg = line[i];
            if (arg.equals("-h")) {
                host = line[++i];
            } else if (arg.equals("-p")) {
                port = Integer.parseInt(line[++i]);
            } else {
                out.println("Usage error: Incorrect parameter(s)");
                PrintUsage();
                return false;
            }
        }

        // host argument validation
        try {
            serveraddr = InetAddress.getByName(host);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return false;
        }

        // Port is out or range
        return ((port > 0) && (port <= 65535));
    }

//---------------------------------------------

    /**
     * Print program usage
     */
    private static void PrintUsage() {
        final String usage = "java quoteUDClient [-h host] [-p port]"
                + "\n\nDESCRIPTION: Quote of day UDP client"
                + "\n\nArguments:"
                + "\n\t-h host (optional): host is a domain name or IP of quote of day server. Default value \"localhost\"."
                + "\n\t-p port (optional): port is the  UDP of quote of day server. Default value 17.";
        out.println(usage);

    }
//---------------------------------------------


    public static void main(String[] args) {


        //Declaramos alguna variable
        byte[] buffer = new byte[65507]; //buffer for UDP maximum payload
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // packet to receive/send
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(in)); //To read stdin
        String msg; //String read from stdin
        String received; //String for received data

        // **** Parsing command line
        if (!ParseInput(args)) {
            exit(1);
        }

        //TODO 1: Enviar una petición UDP al servidor para solicitar la "cita del día"
        //      La dirección del servidor está en el atributo "InetAddress serveraddr"
        //      El puerto del servidor está en el atributo "int port"
        try (DatagramSocket socketudp = new DatagramSocket()) {

            while ((msg = stdIn.readLine()) != null) {
                buffer = msg.getBytes();
                DatagramPacket requestPacket = new DatagramPacket(buffer, buffer.length, serveraddr, port);
                socketudp.send(requestPacket);
                //TODO 2: Recibir la respuesta del servidor con la "cita del día" e imprimirla por pantalla
                DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length);
                socketudp.receive(responsePacket);
                received = new String(responsePacket.getData(), 0, responsePacket.getLength());
                out.println("The quote of the day is:" + received);

                //TODO 3: Cerrar el socket.

                // Para que cerrar, si cierro salta error, preguntar en clase
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
