#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk 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 needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.raritan import *  # pylint: disable=wildcard-import,unused-wildcard-import

raritan_pdu_plugs_default = (
    '"on"'  # only to be downwards compatible and can be removed any decade now.
)


def parse_raritan_pdu_plugs(info):
    parsed = {}

    for outlet_label, outlet_name, outlet_state in info:
        state = raritan_pdu_plug_state.get(outlet_state, "unknown")
        parsed[outlet_label] = {"state": state, "outlet_name": outlet_name}

    return parsed


def inventory_raritan_pdu_plugs(parsed):
    for key, value in parsed.items():
        if (state := value["state"]) != "unknown":
            yield key, {"discovered_state": state}


@get_parsed_item_data
def check_raritan_pdu_plugs(_no_item, params, data):
    if outlet_name := data.get("outlet_name"):
        yield 0, outlet_name

    state = data["state"]
    expected_state = params.get("required_state") or params["discovered_state"]

    if state != expected_state:
        yield (2, "Status: %s (expected: %s)" % (state, expected_state))
    else:
        yield 0, "Status: %s" % state


check_info["raritan_pdu_plugs"] = {
    "inventory_function": inventory_raritan_pdu_plugs,
    "parse_function": parse_raritan_pdu_plugs,
    "check_function": check_raritan_pdu_plugs,
    "service_description": "Plug %s",
    "group": "plugs",
    "snmp_info": (
        ".1.3.6.1.4.1.13742.6",
        [
            "3.5.3.1.2",  # Outlet-Label (Index) (PDU identifier of the outlet)
            "3.5.3.1.3",  # OutletName (eigene vergebene Bezeichnung für den Ausgang)
            "4.1.2.1.3",  # Outlet state at present (sh.o. outlet_state_info im check)
        ],
    ),
    "snmp_scan_function": lambda oid: oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.4.1.13742.6")
    and (
        oid(".1.3.6.1.4.1.13742.6.3.2.1.1.3.1").startswith("PX2-2")
        or oid(".1.3.6.1.4.1.13742.6.3.2.1.1.3.1").startswith("PX3")
    ),
}
