#!/usr/bin/env python3
"""
This code will simply query the voip API, and parse the json response to get the list of
servers. Sounds familiar, doesn't it?
"""
import requests


def get_servers():
    """
    Query the voip api with getServersInfo
    :return: List of server host names
    """

    url = ("https://voip.ms/api/v1/rest.php?"
           "api_username=pythonedustudent@gmail.com&"
           "api_password=Kqmqa9xmqe&"
           "method=getServersInfo")

    try:
        in_page = requests.get(url, timeout=10)
    except (requests.ConnectionError, requests.Timeout) as ex:
        print(ex)
        exit()
    # Decode the json with request's built-in parser. Can throw ValueErrors if not a json
    # object, which is why we try to catch ValueError when running this.
    server_info = in_page.json()
    if server_info["status"] != "success":
        raise IOError("The query was unsuccessful, status is {}"
                      "".format(server_info["status"]))
    server_list = list()

    for entry in server_info['servers']:
        # Just return the server hostname as it is all we need. Place a breakpoint here to
        # look at the other information, if desired.
        server_list.append(entry["server_hostname"])

    return server_list


if __name__ == '__main__':
    try:
        voip_servers = get_servers()
    except (IOError, ValueError) as err:
        # Catch the IOError that can be thrown in parse_json
        print(err)
        exit(1)

    print("List of voip.ms server host names:\n")
    for host_name in voip_servers:
        print(host_name)
