# Author:
# Date: 2-Apr-2017
# Ex1: Basic server communication - Server Side
# Short description:
# The server deals with 'only' 4 commands: TIME, NAME, RAND and EXIT.
# The server can deal with an imperfect client which sends other commands by mistake.
# At first, the server calculates the length of the msg to be sent,
# it then and send this information to the client via a 4 bytes msg.
# This is done so the client can allocate the appropriate resources in order to receive the entire msg.

import socket
from datetime import datetime
from random import randint

SRC_PORT = 1729
SRVR_NAME = "SuperDuper"

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('0.0.0.0', SRC_PORT))
server_socket.listen(1)

client_socket, address = server_socket.accept()

#while data != "EXIT":
while 1:
    data = client_socket.recv(4)

    # checks if the request is for 'time'
    if data == "TIME":
        now = datetime.now()
        server_msg = str(now.hour).zfill(2)+":"+str(now.minute).zfill(2)+":"+str(now.second).zfill(2)
        msg_len = str(len(server_msg)).zfill(4)
        client_socket.send(msg_len)
        client_socket.send(server_msg)

    # checks if the request is for 'name'
    elif data == "NAME":
        server_msg = SRVR_NAME
        msg_len = str(len(server_msg)).zfill(4)
        client_socket.send(msg_len)
        client_socket.send(server_msg)

    # checks if the request is for 'rand'
    elif data == "RAND":
        server_msg = str(randint(2, 9))
        msg_len = str(len(server_msg)).zfill(4)
        client_socket.send(msg_len)
        client_socket.send(server_msg)

    # checks if the request is for 'exit'
    elif data == "EXIT":
        print "Last Data Received from Client:", data, "\nClosing...."
        break

    # if the request is not recognized then...
    else:
        server_msg = "No such request"
        msg_len = str(len(server_msg)).zfill(4)
        client_socket.send(msg_len)
        client_socket.send(server_msg)


# closing the connection and the server
client_socket.close()
server_socket.close()