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

ups_power_default_levels = (20, 1)  # warning / critical


def check_ups_power(item, params, info):
    warn, crit = params
    for idx, _raw_voltage, raw_power in info:
        if idx == item:
            power = saveint(raw_power)
            # Some "RPS SpA" systems are not RFC conform in this value.
            # The values can get negative but should never be.
            if power < 0:
                power *= -1

            perfdata = [("power", power, warn, crit, 0)]
            infotext = "power: %dW (warn/crit at %dW/%dW)" % (power, warn, crit)

            if power <= crit:
                return (2, infotext, perfdata)
            if power <= warn:
                return (1, infotext, perfdata)
            return (0, infotext, perfdata)

    return (3, "Phase %s not found in SNMP output" % item)


check_info["ups_power"] = {
    "inventory_function": lambda i: discovery_ups_generic(i, "ups_power_default_levels"),
    "check_function": check_ups_power,
    "service_description": "Power phase %s",
    "has_perfdata": True,
    "group": "epower",
    "snmp_info": (".1.3.6.1.2.1.33.1.4.4.1", [0, 2, 4]),
    "snmp_scan_function": ups_generic_scan_function,
}
