# Author:
# Date: 2-Apr-2017
# Ex1: Basic server communication - Client Side
# Short description:
# The client supports 'only' 4 commands to the server, TIME, NAME, RAND and EXIT.
# Each has its own number assigned. It prohibits other commands and/or non-numeric input values.
# At first, the client receives the length of the msg by a 4 bytes field from the server.
# After that, it allocates the necessary resources in order to recieve the entire msg.

import socket

HOST_IP = '127.0.0.1'
DST_PORT = 1729

socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST_IP, DST_PORT))

#while user_option != 4:
while 1:
    print 40 * "*"
    str_in = raw_input("Please choose one of the following options:\n"
                       "1-TIME\n"
                       "2-NAME\n"
                       "3-RAND\n"
                       "4-EXIT\n"
                       "Your choice:")

    # checks if user input consists of numeric values only
    if str_in.isdigit():
        user_option = int(str_in)

    else:
        user_option = 0

    # checks if the user requested 'time'
    if user_option == 1:
        user_msg = "TIME"
        socket1.send(user_msg)
        data_len = socket1.recv(4)
        data = socket1.recv(int(data_len))
        print "<response:>",data

    # checks if the user requested 'name'
    elif user_option == 2:
        user_msg = "NAME"
        socket1.send(user_msg)
        data_len = socket1.recv(4)
        data = socket1.recv(int(data_len))
        print "<response:>",data

    # checks if the user requested 'rand'
    elif user_option == 3:
        user_msg = "RAND"
        socket1.send(user_msg)
        data_len = socket1.recv(4)
        data = socket1.recv(int(data_len))
        print "<response:>",data

    # checks if the user requested 'exit'
    elif user_option == 4:
        user_msg = "EXIT"
        socket1.send(user_msg)
        break

    else:
        print "Such an option does not exist, try again..."

# closing the socket
socket1.close()