#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

import calendar

# NOTE: Careful when replacing the *-import below with a more specific import. This can cause
# problems because it might remove variables from the check-context which are necessary for
# resolving legacy discovery results such as [("SUMMARY", "diskstat_default_levels")]. Furthermore,
# it might also remove variables needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.graylog import *  # pylint: disable=wildcard-import,unused-wildcard-import

# <<<graylog_cluster_traffic>>>
# {"to": "2019-09-20T12:00:00.000Z", "output": {"2019-09-17T03:00:00.000Z":
# 6511247, "2019-09-18T14:00:00.000Z": 176026381, "2019-09-08T08:00:00.000Z":
# 5879007, "2019-09-15T17:00:00.000Z": 6125353, "2019-09-19T00:00:00.000Z":
# 171947147, "2019-09-04T21:00:00.000Z": 3898949, "2019-09-09T04:00:00.000Z":
# 7305970, "2019-09-07T02:00:00.000Z": 5892132, "2019-09-15T13:00:00.000Z":
# 5918729, "2019-09-17T01:00:00.000Z": 6204003, "2019-09-03T20:00:00.000Z":
# 3491202, "2019-09-17T06:00:00.000Z": 12998748, "2019-09-12T22:00:00.000Z":
# 10281903, "2019-09-06T12:00:00.000Z": 11985705, "2019-09-05T16:00:00.000Z":
# 6598880, "2019-09-13T21:00:00.000Z": 6335781, "2019-09-18T08:00:00.000Z":
# 177931813, "2019-09-15T22:00:00.000Z": 6131828, "2019-09-18T10:00:00.000Z":
# 178435781, "2019-09-15T02:00:00.000Z": 5913174, "2019-09-18T12:00:00.000Z":
# 180571316, "2019-09-17T09:00:00.000Z": 17555409, "2019-09-16T09:00:00.000Z":
# 15022425, "2019-09-10T21:00:00.000Z": 7688443}}


def check_graylog_cluster_traffic(no_item, params, parsed):
    if parsed is None:
        return

    for key, infotext in [
        ("input", "Input"),
        ("output", "Output"),
        ("decoded", "Decoded"),
    ]:

        traffic_value = parsed.get(key, []).get(parsed["to"])
        if traffic_value is not None:

            yield check_levels(
                traffic_value,
                "graylog_%s" % key,
                params.get(key),
                infoname=infotext,
                human_readable_func=get_bytes_human_readable,
            )

    last_updated = parsed.get("to")
    if last_updated is not None:
        local_timestamp = calendar.timegm(time.strptime(last_updated, "%Y-%m-%dT%H:%M:%S.%fZ"))

        yield 0, "Last updated: %s" % get_timestamp_human_readable(local_timestamp)


check_info["graylog_cluster_traffic"] = {
    "parse_function": parse_graylog_agent_data,
    "check_function": check_graylog_cluster_traffic,
    "inventory_function": discover_single,
    "service_description": "Graylog Cluster Traffic",
    "has_perfdata": True,
    "group": "graylog_cluster_traffic",
}
