import urllib3
import certifi


def get_paged(ctx, rqst):
    """
    Make a GET request to a NuvIoT paged data source will return a string that includes JSON for the response.

    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.

    contentType: 
        Optional content type parameter used set the Accept HTTP header, defaults to empty.

    pageSize:
        Optional page size parameter used to make list requests, defaults to 50
    """    
    if ctx.auth_type == 'user':
        headers={'Authorization': 'Bearer ' + ctx.auth_token, 'x-pagesize' : rqst.pageSize}
    else:
        headers={'Authorization': 'APIKey ' + ctx.client_id + ':' + ctx.client_token, 'x-pagesize' : rqst.pageSize}    

    http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
    url = ctx.url + rqst.path
    r = http.request("GET", url, headers=headers, preload_content=False)
    responseJSON = ''
    for chunk in r.stream(32):
        responseJSON += chunk.decode("utf-8")

    r.release_conn()
    
    if r.status > 299:
        print('Failed http call, response code: ' + str(r.status))
        print('Url: ' + url)
        print('Headers: ' + str(headers))
        print(responseJSON)
        print('--------------------------------------------------------------------------------')
        print()
        return None
      

    return responseJSON