#!/usr/bin/env python3.4 
import socket
import json
import struct
import sys
from rsa_skeleton import *

#based on http://stackoverflow.com/questions/17667903/python-socket-receive-large-amount-of-data
#read next message from socket (first 4 bytes are the length of the next message ("payload length"))    
def recv_msg(socket):
    raw_msglen = recvall(socket, 2) 
    if not raw_msglen:
        return None
    msglen = struct.unpack('>H', raw_msglen)[0]
    # Read the message data
    return recvall(socket, msglen)

# Helper function to recv n bytes or return None if EOF is hit
def recvall(socket, n):
    data = b''
    while len(data) < n:
        packet = socket.recv(n - len(data))
        if not packet:
            return None
        data += packet
    return data
        
#function to receive a JSON formated string from the given socket and return it (most likely a dictionary)
def recv_json(socket):
    received = recv_msg(socket)
    if not received:
        return None
    else:
        received=received.decode() 

    try:
        received = json.loads(received) 

        if 'Error' in received.keys():
            print("Error:")
            print(received["Error"])
            print("stopping program execution...")
            sys.exit()
    except Exception as e:
        print("Something went wrong when interpreting the received string as JSON!\nCheck format: %s"% received)
        print("Exception: %s"%e)
        return None   
    return received 

#send a message over the socket, leading with 4 byte message size header
def sendMessage(socket, msg):
    if len(msg)>65536:
        print("Maximum allowed length for messages is 65kB!")        
        sys.exit()
    msg = struct.pack('>H', len(msg)) + msg.encode() #max 65 kb
    socket.sendall(msg)

#Helper function to send a object (most likely a dictionary in our case) as JSON String
def send_json(socket,obj):
    try:
        sendMessage(socket,json.dumps(obj))
    except Exception as e:
        print("Something went wrong when sending the object or transforming it to a JSON string.\n")
        print("Exception: %s"%e)
        sys.exit()

#################################################
#Only change functions below this line
#################################################

def main():
    HOST = '131.159.15.68'
    PORT = 20006            
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    #we use JSON as notation to transmit our data.(at least for this time, next time we will change the format once again ;))
    s.connect((HOST, PORT))
 
    result=recv_json(s)
    print("Received: ",result)
    
    #Integrate the message exchange with the server here to enter your tag in the Database.
    #You will need a working RSA Implementation to do so.
    # [YOUR TASK STARTS HERE]

    # ...

    # [YOUR TASK ENDS HERE]
    s.close()




main()

