import socket
import sys
import os

HOST = sys.argv[1]
PORT = int(sys.argv[2])

s = socket.socket()
try:
    s.connect((HOST, PORT))
except:
    raise Exception("Device not available to download from.")

STAY = True

def ben(string):
    return bytes(string.encode("utf-8"))
def bde(binary):
    return str(binary.decode("utf-8"))

while STAY == True:
    FILENAME = input("[SERVER]: Enter filename => ")
    s.send(ben(FILENAME))
    response = bde(s.recv(1024))
    if response[:6] == "EXISTS":
        filesize = float(response[6:])
        confirm = input("[SERVER]: "+FILENAME+" is "+str(filesize)+" bytes, download? (Y/N) => ").upper()
        if confirm == "Y":
            s.send(ben("OK"))
            newname = input("[DEVICE]: Name new file => ")
            f = open(newname, "wb")
            data = s.recv(1024)
            totalRecv = len(data)
            f.write(data)
            while totalRecv < filesize:
                data = s.recv(1024)
                totalRecv += len(data)
                f.write(data)
                print(str((totalRecv/float(filesize))*100)+"% complete")

            print("Download complete!")
            f.close()
        elif confirm == "N":
            pass
    else:
        print("[SERVER]: Does not exist!")
