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

# 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.fan import *  # pylint: disable=wildcard-import,unused-wildcard-import

# 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.genua import *  # pylint: disable=wildcard-import,unused-wildcard-import

factory_settings["genua_fan_default_levels"] = {
    "lower": (2000, 1000),
    "upper": (8000, 8400),
}


def inventory_genua_fan(info):
    # remove empty elements due to alternative enterprise id in snmp_info
    info = [_f for _f in info if _f]

    if not info:
        return

    inventory = []
    for fanName, _fanRPM, _fanState in info[0]:
        inventory.append((fanName, {}))
    return inventory


def check_genua_fan(item, params, info):
    # remove empty elements due to alternative enterprise id in snmp_info
    info = [_f for _f in info if _f]

    map_states = {
        "1": (0, "OK"),
        "2": (1, "warning"),
        "3": (2, "critical"),
        "4": (2, "unknown"),
        "5": (2, "unknown"),
        "6": (2, "unknown"),
    }

    for line in info[0]:
        fanName, fanRPM, fanState = line
        if fanName != item:
            continue

        rpm = saveint(fanRPM)
        state, state_readable = map_states[fanState]
        yield state, "Status: %s" % state_readable
        yield check_fan(rpm, params)


check_info["genua_fan"] = {
    "inventory_function": inventory_genua_fan,
    "check_function": check_genua_fan,
    "group": "hw_fans",
    "service_description": "FAN %s",
    "has_perfdata": True,
    "snmp_info": [
        (".1.3.6.1.4.1.3717.2.1.1.1.1", ["2", "3", "4"]),  # "fanName"  # "fanRPM"  # "fanState"
        (".1.3.6.1.4.1.3137.2.1.1.1.1", ["2", "3", "4"]),  # "fanName"  # "fanRPM"  # "fanState"
    ],
    "snmp_scan_function": scan_genua,
    "default_levels_variable": "genua_fan_default_levels",
}
