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

alcatel_power_operstate_map = {
    "1": "up",
    "2": "down",
    "3": "testing",
    "4": "unknown",
    "5": "secondary",
    "6": "not present",
    "7": "unpowered",
    "9": "master",
}

alcatel_power_no_power_supply_info = "no power supply"

alcatel_power_type_map = {
    "0": alcatel_power_no_power_supply_info,
    "1": "AC",
    "2": "DC",
}

AlcatelPowerEntry = collections.namedtuple(  # pylint: disable=collections-namedtuple-call
    "AlcatelPowerEntry",
    [
        "oper_state_readable",
        "power_type",
    ],
)


def parse_alcatel_power(info):
    parsed = {}
    for oidend, status, power_type in info:
        parsed.setdefault(
            oidend,
            AlcatelPowerEntry(
                alcatel_power_operstate_map.get(status, "unknown[%s]" % status),
                alcatel_power_type_map.get(power_type, alcatel_power_no_power_supply_info),
            ),
        )
    return parsed


@discover
def inventory_alcatel_power(_oidend, device):
    return (
        device.power_type != alcatel_power_no_power_supply_info
        and device.oper_state_readable != "not present"
    )


@get_parsed_item_data
def check_alcatel_power(item, _no_params, device):
    if device.oper_state_readable == "up":
        state = 0
    else:
        state = 2
    yield state, "[%s] Operational status: %s" % (device.power_type, device.oper_state_readable)


check_info["alcatel_power"] = {
    "parse_function": parse_alcatel_power,
    "check_function": check_alcatel_power,
    "inventory_function": inventory_alcatel_power,
    "service_description": "Power Supply %s",
    "snmp_scan_function": alcatel_networking_products_scan_function,
    "snmp_info": (
        ".1.3.6.1.4.1.6486.800.1.1.1.1.1.1.1",  # MIB object "chasEntPhysicalEntry"
        [
            OID_END,
            2,  # MIB object "chasEntPhysOperStatus":
            #     up(1), down(2), testing(3), unknown(4),
            #     secondary(5), notPresent(6), unpowered(7), master(9)
            36,  # MIB object "chasEntPhysPowerType":
            #     0 no power supply, 1 ac, 2 dc (not available on old devices)
        ],
    ),
}
