import urllib3
import certifi


def post_json(ctx, path, json):
    """
    Make a POST request with a JSON payload to be sent to a NuvIoT endpoint.
    
    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.

    json:
        JSON object to be posted

    Returns
    -------
        Will return any JSON returned from the server, if the response code is not a success code an exception will be raised.
    """
    if ctx.auth_type == 'user':
        headers={'Authorization': 'Bearer ' + ctx.auth_token, 'Content-Type':'application/json'}
    else:
        headers={'Authorization': 'APIKey ' + ctx.client_id + ':' + ctx.client_token, 'Content-Type':'application/json'}
    
    url = ctx.url + path

    encoded_data = json.encode('utf-8')
    
    http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
    r = http.request('POST', url,
             headers=headers,
             preload_content=False,
             body=encoded_data)
    
    responseJSON = ''
    responseStatus = r.status
    for chunk in r.stream(32):
        responseJSON += chunk.decode("utf-8")
    
    r.release_conn()

    if responseStatus > 299:
        print('Failed http call, response code: ' + str(responseStatus))
        print('Url: ' + url)
        print('Headers: ' + str(headers))
        print(responseJSON)
        print('--------------------------------------------------------------------------------')
        print()
        raise Exception("Could not post JSON to %s" % url)

    return responseJSON