#!/usr/bin/env python
# coding: utf-8

from __future__ import print_function

import click as _click
import requests as _requests

@_click.command()
@_click.option("--url", envvar="ICINGA_API_URL", help="Icinga API URL")
@_click.option("--user", envvar="ICINGA_API_USER", help="Icinga API user")
@_click.option("--pw", envvar="ICINGA_API_PW", help="Icinga API password")
@_click.argument("service_name", required=False)
def cli(url, user, pw, service_name):
    """ Return hostnames for the selected icinga services """
    if service_name:
        filters = """ service.state >= 1 && service.name == "{}" """.format(service_name)
    else:
        filters = """ service.state >= 1 """

    response = _requests.get(
        "{}v1/objects/hosts".format(url),
        params={"filter": filters, "attrs": "host_name"},
        auth=(user, pw),
        verify=False,
    )

    #response.raise_for_status()

    services = response.json()
    print(response.json())

    for service in services:
        print(service["attrs"]["host_name"])


if __name__ == "__main__":
    cli() # pylint: disable=no-value-for-parameter
