import requests
import json


def update_network(platform, key, client, net_id, new_name):

    """
    Updates the name of a network via the API.

    :param platform:    URL of the RiskSense Platform to be queried.
    :type  platform:    str

    :param key:         API Key.
    :type  key:         str

    :param client:      Client ID to be queried.
    :type  client:      int

    :param net_id:      Identifier for network to be updated.
    :type  net_id:      int

    :param new_name:    Desired new name for the network to be updated.
    :type  new_name:    str

    :return:    Returns a dictionary containing the response from the platform.
    :rtype:     dict
    """

    #  Assemble the URL for the API request.
    url = platform + "/api/v1/client/" + str(client) + "/network/" + str(net_id)

    #  Define the header for the API request.
    header = {
        "x-api-key": key,
        "content-type": "application/json",
        "Cache-Control": "no-cache"
    }

    #  Define the body for the API request
    body = {
        "name": new_name
    }

    #  Submit the update request to the API
    response = requests.put(url, headers=header, data=json.dumps(body))

    #  If the request is successful...
    if response and response.status_code == 200:
        network_response = json.loads(response.text)

    #  If the request is unsuccessful...
    else:
        print("An error occurred updating the network via API.")
        print(f"Status Code: {response.status_code}")
        print(f"Response: {response.text}")
        exit(1)

    return network_response