#!/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 json

# 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_sources>>>
# {"sources": {"klappclub": 81216}, "range": 0, "total": 1, "took_ms": 28}


def parse_graylog_sources(info):
    parsed = {}

    for line in info:
        sources_data = json.loads(line[0])

        source_name = sources_data.get("sources")
        if source_name is None:
            continue

        for name, messages in source_name.items():

            parsed.setdefault(
                name,
                {
                    "messages": int(messages),
                },
            )

    return parsed


@get_parsed_item_data
def check_graylog_sources(item, params, item_data):
    messages = item_data.get("messages")
    if messages is None:
        return

    return handle_graylog_messages(messages, params)


check_info["graylog_sources"] = {
    "parse_function": parse_graylog_sources,
    "check_function": check_graylog_sources,
    "inventory_function": discover(),
    "default_levels_variable": "graylog_sources_default_levels",
    "service_description": "Graylog Source %s",
    "has_perfdata": True,
    "group": "graylog_sources",
}
