import os
import sys
from ftplib import FTP

from utility.utils import timeit

@timeit
def ftp_server_request(filename, ftp, file_to_write):
    command = f'RETR {filename}'
    response= ftp.retrbinary(command, file_to_write.write )
    return response


def make_request_ftp_client(IP, port, filename, file_loc_to_write):
    '''
    Using ftplib — FTP protocol client.
    :param address:
    :param filename:
    :param file_loc_to_write:
    :return:
    '''
    # Connect to server
    try:
        ftp = FTP()
        ftp.connect(host=IP, port=port)
        ftp.login(user="dummy_user", passwd="12345")
        # catch welcome message from server.
        print(ftp.getwelcome())

    except Exception:
        raise Exception

    file_to_write = os.path.join(file_loc_to_write, f"retrieved_{filename}")
    client_file = open(file_to_write, 'wb')

    # requesting sever for a file and parsing it's response!
    response = ftp_server_request(filename, ftp, client_file)

    if response.startswith('226'):
        print('File Transfered!')
    else:
        print("Transfer didn't happen")

    client_file.close()
    ftp.close()


if __name__=='__main__':
    
    filename = sys.argv[1]
    file_loc_to_write = sys.argv[2]
    SERVER_IP = sys.argv[3] # "127.0.0.1" #http://localhost
    SERVER_PORT = 2121
    
    make_request_ftp_client( SERVER_IP,SERVER_PORT, filename, file_loc_to_write)

