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

# We fetch the following columns from SNMP:
# 2 pethMainPsePower (The nominal power of the PSE expressed in Watts)
# 3 pethMainPseOperStatus (The operational status of the main PSE) (on(1), off(2), faulty(3))
# 4 pethMainPseConsumptionPower (Measured usage power expressed in Watts)

factory_settings["pse_poe_default_levels"] = {"levels": (90.0, 95.0)}


def parse_pse_poe(info):
    """
    parse info data and create dictionary with namedtuples for each OID.

    {
       oid_end : PoeValues(poe_max, poe_used, poe_status, poe_status_detail)
    }

    :param info: parsed snmp data
    :return: dictionary
    """
    poe_dict = {}
    for oid_end, poe_max, pse_op_status, poe_used in info:
        poe_dict[str(oid_end)] = PoeValues(
            poe_max=int(poe_max),
            poe_used=int(poe_used),
            poe_status=int(pse_op_status),
            poe_status_detail=None,
        )
    return poe_dict


def inventory_pse_poe(parsed):
    return [(oid_end, {}) for oid_end in parsed]


@get_parsed_item_data
def check_pse_poe(item, params, poe_data):
    return check_poe_data(params, poe_data)


check_info["pse_poe"] = {
    "default_levels_variable": "pse_poe_default_levels",
    "parse_function": parse_pse_poe,
    "check_function": check_pse_poe,
    "inventory_function": inventory_pse_poe,
    "service_description": "POE%s consumption ",
    "has_perfdata": True,
    "snmp_scan_function": lambda oid: oid(".1.3.6.1.2.1.105.1.3.1.1.*"),
    "snmp_info": (".1.3.6.1.2.1.105.1.3.1.1", [OID_END, "2", "3", "4"]),
}
