import urllib3
import certifi


def download_file(ctx, path, dest, accept = ""):
    """
    Download a file to a NuvIoT
    
    Parameters
    ----------
    ctx:
        Context Object that defines how this method should call the server to include authentication.

    path:
        Path used to make the request, the auth and server information will be used from the ctx object.

    dest:
        The full path including the file name and extension of where the downloaded file should be saved.

    Returns
    -------
        Will return True if the file is download and saved locally, other wise it will return False.
    """
    if ctx.auth_type == 'user':
        headers={'Authorization': 'Bearer ' + ctx.auth_token}
    else:
        headers={'Authorization': 'APIKey ' + ctx.client_id + ':' + ctx.client_token}
       
    if(accept != ""):
        headers['Accept'] = accept
    
    url = ctx.url + path
    
    print("Downloading file: %s" % url)

    chunk_size = 65536
        
    http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
    r = http.request("GET", url, headers=headers, preload_content=False)
 
    if r.status > 299:
        print('Failed http %d url: %s' % (r.status, url))
        print('Headers: ' + str(headers))
        print('--------------------------------------------------------------------------------')
        print()
        r.release_conn()
        return False

    print('Headers: ' + str(r.headers))
    print('Headers: ' + str(r.headers["Content-Disposition"]))
    with open(dest, 'wb') as out:
        while True:
            data = r.read(65535)
            if not data:
                break
            
            out.write(data)
    r.release_conn()
    return True