#!/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.
"""Zorp FW - connections
This check displays individual connections returned by
  zorpctl szig -r zorp.stats.active_connections
It sums up all connections and checks against configurable maximum values.
"""

factory_settings["zorp_connections"] = {
    "levels": (15, 20),
}


def parse_zorp_connections(info):
    """Creates dict name -> connections
    from info =
    [["Instance <name>:", "walking"], ["zorp.stats.active_connections:", "<Number|'None'>"],
     ["Instance <name>:", "walking"], ["zorp.stats.active_connections:", "<Number|'None'>"],
     ...]
    """
    return {
        instance[1].rstrip(":"): int(state[1]) if state[1] != "None" else 0
        for instance, state in zip(info[::2], info[1::2])
    }


def check_zorp_connections(item, params, parsed):
    """List number of connections for each connection type and check against
    total number of connections"""
    if not parsed:
        return

    yield from ((0, "%s: %d" % elem) for elem in parsed.items())

    yield check_levels(
        sum(parsed.values()),
        "connections",
        params.get("levels"),
        infoname="Total connections",
        human_readable_func=int,
    )


check_info["zorp_connections"] = {  # mypy: ignore
    "parse_function": parse_zorp_connections,
    "inventory_function": lambda parsed: [(None, {})],
    "check_function": check_zorp_connections,
    "service_description": "Zorp Connections",
    "default_levels_variable": "zorp_connections",
    "group": "zorp_connections",
}
