#!/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

factory_settings["poseidon_temp_default_levels"] = {}


def parse_poseidon_temp(info):
    parsed = {}
    if not info:
        return
    for name, state, value_string in info:
        try:
            temp = float(value_string.replace("C", ""))
        except ValueError:
            temp = None
        parsed[name] = {"temp": temp, "status": state}
    return parsed


@get_parsed_item_data
def check_poseidon_temp(item, params, data):
    sensor_states = {
        "0": "invalid",
        "1": "normal",
        "2": "alarmstate",
        "3": "alarm",
    }
    sensor_state_value = data.get("status")
    sensor_state_txt = sensor_states.get(sensor_state_value)
    mk_status = 0
    if sensor_state_value != "1":
        mk_status = 2
    yield mk_status, "Sensor %s, State %s" % (item, sensor_state_txt)

    temp = data.get("temp")
    if temp:
        yield check_temperature(temp, params, "poseidon_temp_%s" % item.replace(" ", "_"))
    else:
        yield 3, "No data for Sensor %s found" % item


check_info["poseidon_temp"] = {
    "parse_function": parse_poseidon_temp,
    "check_function": check_poseidon_temp,
    "inventory_function": discover(),
    "service_description": "Temperatur: %s",
    "has_perfdata": True,
    "group": "temperature",
    "snmp_scan_function": lambda oid: oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.4.1.21796.3"),
    "snmp_info": (".1.3.6.1.4.1.21796.3.3.3.1", ["2", "4", "5"]),
    "default_levels_variable": "poseidon_temp_default_levels",
}
