import socket
import sys
import os
import json
from network_utility import *
from xor import *
cache_dir="./cache/"
try:
	s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,msg:
	print 'Failed to create socket. Error code:'+str(msg[0])+',Error message:'+msg[1]
	sys.exit()
print 'Socket Created'
host = 'localhost'
port = 8005
try:
    remote_ip = socket.gethostbyname( host )
except socket.gaierror:
    #could not resolve
    print 'Hostname could not be resolved. Exiting'
    sys.exit()
print 'Ip address of ' + host + ' is ' + remote_ip
#Connect to remote server
s.connect((remote_ip , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip

#Send some data to remote server
client_id=sys.argv[1]
print "client id is: ",client_id
user_dir="User_"+str(client_id)

message = "This is a user "+client_id+"." 
try :
    #Set the whole string
    s.sendall(message)
except socket.error:
    #Send failed
    print 'Send failed'
    sys.exit()
 
#print 'Message send successfully'
#Now receive data

connect_flag=False
delivery_flag=False
request_flag=False
while True:
    #s.sendall(message)
    if connect_flag==True:
        wait_with_dot(10,3)
        s.sendall("Placement begin.")
        print "Placement begin."
        connect_flag=False
    
    if delivery_flag==True:
        wait_with_dot(10,3)
        s.sendall("Delivery begin.")
        print "Delivery begin."
        delivery_flag=False
        request_flag=True
    
    if request_flag==True:
        request=raw_input("Please input the Delivery Request: ")
        print "Request is: ",request
        s.sendall(request)
        request_flag=False

    reply = s.recv(10000)
    print reply

    if reply=="This is a server.":
        connect_flag=True
    
    if reply=="Placement end.":
        print "Placement has ended."
        delivery_flag=True
        wait_with_dot(27,2)
    if reply=="Delivery end.":
        print "Delivery has ended."

    if reply=="end":
        break

    if is_json(reply):
        json_data=json.loads(reply)
        
        phase=json_data['phase']
        if phase=="placement":
            content=json_data['chunk']
            
            for i in range(len(content)):
                chunk_name=content[i]['title']
                chunk_content=content[i]['content']
                chunk_dir=os.path.join(cache_dir,user_dir,chunk_name)
                with open(chunk_dir,'w') as f:
                    f.write(chunk_content)
            s.sendall("Placement has done.")

        if phase=="delivery":
            content=json_data['chunk']
            #print content
            #for i in range(len(content)):
s.close()
