import requests
import json


def get_group_id_by_name(ome_ip_address: str, group_name: str, headers: dict) -> int:
    """
    Retrieves the ID of a group given its name.

    Args:
        ome_ip_address: The IP address of the OME server
        group_name: The name of the group whose ID you want to resolve.
        headers: Headers used for authentication to the OME server

    Returns: Returns the ID of the group as an integer.

    """

    print("Searching for the requested group.")
    groups_url = "https://%s/api/GroupService/Groups?$filter=Name eq '%s'" % (ome_ip_address, group_name)

    group_response = requests.get(groups_url, headers=headers, verify=False)

    if group_response.status_code == 200:
        json_data = json.loads(group_response.content)

        if json_data['@odata.count'] > 1:
            print("WARNING: We found more than one name that matched the group name: " + group_name +
                  ". We are picking the first entry.")
        if json_data['@odata.count'] == 1 or json_data['@odata.count'] > 1:
            group_id = json_data['value'][0]['Id']
            if not isinstance(group_id, int):
                print("The server did not return an integer ID. Something went wrong.")
                return -1
            return group_id
        else:
            print("Error: We could not find the group " + group_name + ". Exiting.")
            return -1
    else:
        print("Unable to retrieve groups. Exiting.")
        return -1