#!/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.huawei_switch import *  # pylint: disable=wildcard-import,unused-wildcard-import
HuaweiFanData = collections.namedtuple("HuaweiFanData", "fan_present fan_speed")


def parse_huawei_switch_fan(info):
    entities_per_member = {}
    for line in info:
        member_number = line[0].partition(".")[0]
        fan_present = (line[2] == '1')

        try:
            fan_speed = float(line[1])
        except TypeError:
            continue

        entities_per_member.setdefault(member_number, []).append(
            HuaweiFanData(fan_present=fan_present, fan_speed=fan_speed))

    return huawei_item_dict_from_entities(entities_per_member)


def inventory_huawei_switch_fan(parsed):
    for item, item_data in parsed.items():
        if item_data.fan_present:
            yield (item, {})


@get_parsed_item_data
def check_huawei_switch_fan(item, params, item_data):
    levels = params.get('levels', (None, None)) + params.get('levels_lower', (None, None))
    return check_levels(item_data.fan_speed,
                        "fan_perc",
                        levels,
                        human_readable_func=get_percent_human_readable)


check_info['huawei_switch_fan'] = {
    'parse_function': parse_huawei_switch_fan,
    'inventory_function': inventory_huawei_switch_fan,
    'check_function': check_huawei_switch_fan,
    'service_description': 'Fan %s',
    'snmp_info': (
        '.1.3.6.1.4.1.2011.5.25.31.1.1.10.1',
        [
            # OID_END will be something like <stack id>.<fan index>
            # we are only interested in the stack id before the dot
            OID_END,
            '5',  # hwEntityFanSpeed
            '6',  # hwEntityFanPresent
        ],
    ),
    'snmp_scan_function': huawei_switch_scan_function,
    'has_perfdata': True,
    'group': 'hw_fans_perc',
}
