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


def parse_mbg_lantime_ng_fan(info):
    parsed = {}
    fan_states = {
        "0": (3, "not available"),
        "1": (2, "off"),
        "2": (0, "on"),
    }
    fan_errors = {
        "0": (0, "not available"),
        "1": (0, "no"),
        "2": (2, "yes"),
    }

    for line in info:

        index, fan_status, fan_error = line
        if not index:
            continue

        fan_state, fan_state_name = fan_states.get(
            fan_status,
            (3, "not available"),
        )
        error_state, error_name = fan_errors.get(
            fan_error,
            (3, "not available"),
        )

        parsed.setdefault(
            index,
            {
                "status": {"state": fan_state, "name": fan_state_name},
                "error": {"state": error_state, "name": error_name},
            },
        )

    return parsed


@get_parsed_item_data
def check_mbg_lantime_ng_fan(item, _no_params, parsed):
    if not parsed:
        return

    fan_status = parsed["status"]
    yield fan_status["state"], "Status: %s" % fan_status["name"]

    fan_error = parsed["error"]
    yield fan_error["state"], "Errors: %s" % fan_error["name"]


check_info["mbg_lantime_ng_fan"] = {
    "check_function": check_mbg_lantime_ng_fan,
    "parse_function": parse_mbg_lantime_ng_fan,
    "inventory_function": discover(lambda k, value: value["status"]["name"] != "not available"),
    "service_description": "Fan %s",
    "snmp_info": (
        ".1.3.6.1.4.1.5597.30.0.5.1.2.1",
        [
            1,  # mgbLtNgSysFanIndex
            2,  # mgbLtNgSysFanStatus
            3,  # mgbLtNgSysFanError
        ],
    ),
    "snmp_scan_function": snmp_scan_mbg_lantime_ng_hw,
}
