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

# 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

factory_settings["ups_bat_temp_default"] = {
    "levels": (40, 50),
}


def format_item_ups_bat_temp(name, new_format):
    if new_format:
        return "Battery %s" % name
    return name


def inventory_ups_bat_temp(info):
    # 2nd condition is needed to catch some UPS devices which do not have
    # any temperature sensor but report a 0 as upsBatteryTemperature. Skip those lines
    if len(info) > 0 and saveint(info[0][1]) != 0:
        return [(format_item_ups_bat_temp(line[0], True), "ups_bat_temp_default") for line in info]


def check_ups_bat_temp(item, params, info):
    for line in info:
        name = format_item_ups_bat_temp(line[0], "Battery" in item)
        if name == item:
            status, infotext, perfdata = check_temperature(
                int(line[1]), params, "ups_bat_temp_%s" % item
            )
            perfdatanew = [perfdata[0] + (80,)]
            return status, infotext, perfdatanew


check_info["ups_bat_temp"] = {
    "inventory_function": inventory_ups_bat_temp,
    "check_function": check_ups_bat_temp,
    "default_levels_variable": "ups_bat_temp_default",
    "service_description": "Temperature %s",
    "has_perfdata": True,
    "group": "temperature",
    "snmp_info": (
        ".1.3.6.1.2.1.33.1",
        [
            "1.5",  # upsIdentName
            "2.7",  # upsBatteryTemperature
        ],
    ),
    "snmp_scan_function": ups_generic_scan_function,
}
