#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2020             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Checkmk.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# <<<rabbitmq_queues>>>
# {"memory": 14332, "message_stats": {"publish": 1, "publish_details": {"rate":
# 0.0}}, "messages": 1, "messages_ready": 1, "messages_unacknowledged": 0,
# "name": "my_queue2", "node": "rabbit@my-rabbit", "state": "running", "type":
# "classic"}
# {"memory": 13548, "messages": 0, "messages_ready": 0,
# "messages_unacknowledged": 0, "name": "my_queue2", "node": "rabbit@my-rabbit",
# "state": "running", "type": "classic"}

import json


def parse_rabbitmq_queues(info):
    parsed = {}

    for queues in info:
        for queue_json in queues:
            queue = json.loads(queue_json)

            queue_name = queue.get("name")
            if queue_name is not None:

                parsed.setdefault(
                    queue_name,
                    {
                        "type": queue.get("type"),
                        "state": queue.get("state"),
                        "node": queue.get("node"),
                        "messages": queue.get("messages"),
                        "messages_ready": queue.get("messages_ready"),
                        "messages_unacknowledged": queue.get("messages_unacknowledged"),
                        "memory": queue.get("memory"),
                        "messages_publish": queue.get("message_stats", {}).get("publish"),
                        "messages_publish_rate": queue.get("message_stats", {})
                        .get("publish_details", {})
                        .get("rate"),
                    },
                )

    return parsed


@get_parsed_item_data
def check_rabbitmq_queues(item, params, parsed):
    if not parsed:
        return

    queue_type = parsed.get("type")
    if queue_type is not None:
        yield 0, "Type: %s" % queue_type.title()

    queue_state = parsed.get("state")
    if queue_state is not None:
        state = 0
        if not queue_state:
            state = 2
        yield state, "Is running: %s" % str(queue_state).replace("True", "yes").replace(
            "False", "no"
        )

    queue_node = parsed.get("node")
    if queue_node is not None:
        yield 0, "Running on node: %s" % queue_node

    for msg_key, infotext, param_key in [
        ("messages", "Total number of messages", "msg"),
        ("messages_ready", "Messages ready", "msg_ready"),
        ("messages_unacknowledged", "Messages unacknowledged", "msg_unack"),
        ("messages_publish", "Messages published", "msg_publish_upper"),
        ("messages_publish_rate", "Rate", "msg_publish_rate"),
    ]:

        msg_value = parsed.get(msg_key)
        if msg_value is None:
            continue

        unit = ""
        if "rate" in msg_key:
            unit = "1/s"

        msg_levels_upper = params.get("%s_upper" % param_key, (None, None))
        msg_levels_lower = params.get("%s_lower" % param_key, (None, None))

        yield check_levels(
            msg_value,
            msg_key,
            msg_levels_upper + msg_levels_lower,
            human_readable_func=int,
            unit=unit,
            infoname=infotext,
        )

    queue_memory = parsed.get("memory")
    if queue_memory is not None:
        yield check_levels(
            queue_memory,
            "mem_lnx_total_used",
            params.get("abs_memory"),
            human_readable_func=get_bytes_human_readable,
            infoname="Memory used",
        )


check_info["rabbitmq_queues"] = {
    "parse_function": parse_rabbitmq_queues,
    "check_function": check_rabbitmq_queues,
    "inventory_function": discover(),
    "service_description": "RabbitMQ Queue %s",
    "has_perfdata": True,
    "group": "rabbitmq_queues",
}
