#!/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_in_freq_default_levels = (45, 40)  # warning / critical


def parse_ups_in_freq(info):
    parsed = {}
    for name, freq_str in info:
        try:
            freq = int(freq_str) / 10.0
        except ValueError:
            freq = None
        parsed.setdefault(name, freq)
    return parsed


@discover(default_params="ups_in_freq_default_levels")
def inventory_ups_in_freq(key, freq):
    return freq is not None and freq > 0


def check_ups_in_freq(item, params, parsed):
    freq = parsed.get(item)
    if freq is None:
        return

    infotext = "%.1f Hz" % freq
    state = 0
    warn, crit = params
    if freq < crit:
        state = 2
    elif freq < warn:
        state = 1
    if state:
        infotext += " (warn/crit below %s Hz/%s Hz)" % (warn, crit)
    return state, infotext, [("in_freq", freq, warn, crit, 30, 70)]


check_info["ups_in_freq"] = {
    "parse_function": parse_ups_in_freq,
    "inventory_function": inventory_ups_in_freq,
    "check_function": check_ups_in_freq,
    "service_description": "IN frequency phase %s",
    "has_perfdata": True,
    "group": "efreq",
    "snmp_info": (
        ".1.3.6.1.2.1.33.1.3.3.1",
        [
            0,
            2,  # UPS-MIB.txt::upsInputFrequency
        ],
    ),
    "snmp_scan_function": ups_generic_scan_function,
}
