import requests
import json


def post_request(url, json_payload, **kwargs):
    """
    post_request function is used to send a POST request in order to interact
    with remote services through rest apis

    url: url to the remote service
    json_payload: json object containing remote service input parameters
    kwargs: additional parameters to be scpecified such as 'cp_cl_api_key'
        to authenticate
    """
    try:
        if 'cp_cl_api_key' in kwargs:
            # prepare url to send a post request
            url = url + "/post"
            # prepare headers
            headers = {'Content-Type': 'application/json', 'cp_api_key': kwargs['cp_cl_api_key']}
            # send request
            print(json_payload)
            response = requests.post(url=url, headers=headers, json=json_payload)
        else:
            # no service key has been specified
            print("no cp_cl_api_key has been specified")
            return {}
    except:
        # if any error occurs print it
        print("Network exception occurred with POST request!!!")
        return {}
    status_code = response.status_code
    print("post_request: received response with status code {}".format(status_code))
    json_data = json.loads(response.text)
    return json_data