#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk 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.

# NOTE: Careful when replacing the *-import below with a more specific import. This can cause
# problems because it might remove variables needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.wmi import *  # pylint: disable=wildcard-import,unused-wildcard-import

# source for these defaults:
# https://blogs.technet.microsoft.com/samdrey/2015/01/26/exchange-2013-performance-counters-and-their-thresholds/
factory_settings["msexch_rpcclientaccess_defaultlevels"] = {
    "latency_s": (0.2, 0.25),
    "requests": (30, 40),
}


def discover_msexch_rpcclientaccess(parsed):
    return inventory_wmi_table_total(parsed)


def check_msexch_rpcclientaccess(_no_item, params, parsed):
    # despite the source being raw-data, the averaged latency is
    # pre-processed
    table = parsed[""]

    try:
        latency = table.get(0, "RPCAveragedLatency")
    except KeyError:
        latency = None
    if latency is not None:
        yield check_levels(
            float(latency) / 1000.0,
            "average_latency_s",
            get_levels_quadruple(params["latency_s"]),
            infoname="Average latency",
            human_readable_func=lambda value: f"{(value*1000.0):.2f} ms",
        )
    yield from wmi_yield_raw_persec(
        table,
        None,
        "RPCRequests",
        infoname="RPC Requests/sec",
        perfvar="requests_per_sec",
        levels=params["requests"],
    )
    yield from wmi_yield_raw_counter(
        table, None, "UserCount", infoname="Users", perfvar="current_users"
    )
    yield from wmi_yield_raw_counter(
        table, None, "ActiveUserCount", infoname="Active users", perfvar="active_users"
    )


check_info["msexch_rpcclientaccess"] = {
    "inventory_function": discover_msexch_rpcclientaccess,
    "check_function": check_msexch_rpcclientaccess,
    "parse_function": parse_wmi_table,
    "has_perfdata": True,
    "service_description": "Exchange RPC Client Access",
    "group": "msx_rpcclientaccess",
    "default_levels_variable": "msexch_rpcclientaccess_defaultlevels",
}
