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


def detect_webtherm(oid):
    return oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.4.1.5040.1.2.")


def parse_wut_webtherm(info):
    map_sensor_type = {
        "1": "temp",
        "2": "humid",
        "3": "air_pressure",
    }
    parsed = {}
    for index, reading_de, reading_en in info:
        if reading_en:
            reading_str = reading_en
        elif reading_de:
            reading_str = reading_de.replace(",", ".")
        else:
            reading_str = ""

        webtherm_type, sensor_id = index.split(".")
        # Dependent on webtherm_type we have to determine
        # which sensors are available. Feel free to
        # declare more sensor types here.
        if "---" not in reading_str and reading_str:
            # We have only temperature sensors
            if int(webtherm_type) <= 9:  # TODO: this is just a guess
                parsed[sensor_id] = {
                    "type": "temp",
                    "reading": float(reading_str),
                }
            # Here we have three different types of sensors:
            # 1 = temp, 2 = humid, 3 = air pressure
            else:
                parsed[sensor_id] = {
                    "type": map_sensor_type[sensor_id],
                    "reading": float(reading_str),
                }

    return parsed


#   .--Temperature---------------------------------------------------------.
#   |     _____                                   _                        |
#   |    |_   _|__ _ __ ___  _ __   ___ _ __ __ _| |_ _   _ _ __ ___       |
#   |      | |/ _ \ '_ ` _ \| '_ \ / _ \ '__/ _` | __| | | | '__/ _ \      |
#   |      | |  __/ | | | | | |_) |  __/ | | (_| | |_| |_| | | |  __/      |
#   |      |_|\___|_| |_| |_| .__/ \___|_|  \__,_|\__|\__,_|_|  \___|      |
#   |                       |_|                                            |
#   +----------------------------------------------------------------------+
#   |                             main check                               |
#   '----------------------------------------------------------------------'

factory_settings["wut_webtherm_defaultlevels"] = {
    "levels": (30, 35),
}


def inventory_wut_webtherm(parsed):
    return [(sensor_id, {}) for sensor_id, values in parsed.items() if values["type"] == "temp"]


def check_wut_webtherm(item, params, parsed):
    if item in parsed:
        return check_temperature(parsed[item]["reading"], params, "wut_webtherm_%s" % item)


check_info["wut_webtherm"] = {
    "default_levels_variable": "wut_webtherm_defaultlevels",
    "parse_function": parse_wut_webtherm,
    "inventory_function": inventory_wut_webtherm,
    "check_function": check_wut_webtherm,
    "service_description": "Temperature %s",
    "has_perfdata": True,
    "snmp_info": (
        ".1.3.6.1.4.1.5040.1.2",
        ["1", "2", "3", "6", "7", "8", "9", "16", "18", "36", "37", "38", "42"],
        [
            "1.2.1.1",  # WebGraph-Thermo-Hygro-Barometer-MIB::wtWebGraphThermoBaroSensorNo
            "1.3.1.1",  # WebGraph-Thermo-Hygro-Barometer-MIB::wtWebGraphThermoBaroTempValue
            "1.8.1.1",  # WebGraph-Thermo-Hygro-Barometer-MIB::wtWebGraphThermoBaroTempValuePkt
        ],
    ),
    "snmp_scan_function": detect_webtherm,
    "group": "temperature",
}

# .
#   .--Air Pressure--------------------------------------------------------.
#   |          _    _        ____                                          |
#   |         / \  (_)_ __  |  _ \ _ __ ___  ___ ___ _   _ _ __ ___        |
#   |        / _ \ | | '__| | |_) | '__/ _ \/ __/ __| | | | '__/ _ \       |
#   |       / ___ \| | |    |  __/| | |  __/\__ \__ \ |_| | | |  __/       |
#   |      /_/   \_\_|_|    |_|   |_|  \___||___/___/\__,_|_|  \___|       |
#   |                                                                      |
#   '----------------------------------------------------------------------'


def inventory_wut_webtherm_pressure(parsed):
    return [
        (sensor_id, None)
        for sensor_id, values in parsed.items()
        if values["type"] == "air_pressure"
    ]


def check_wut_webtherm_pressure(item, _no_params, parsed):
    if item in parsed:
        return 0, "%.2f hPa" % parsed[item]["reading"]


check_info["wut_webtherm.pressure"] = {
    "inventory_function": inventory_wut_webtherm_pressure,
    "check_function": check_wut_webtherm_pressure,
    "service_description": "Pressure %s",
}

# .
#   .--Humidity------------------------------------------------------------.
#   |              _   _                 _     _ _ _                       |
#   |             | | | |_   _ _ __ ___ (_) __| (_) |_ _   _               |
#   |             | |_| | | | | '_ ` _ \| |/ _` | | __| | | |              |
#   |             |  _  | |_| | | | | | | | (_| | | |_| |_| |              |
#   |             |_| |_|\__,_|_| |_| |_|_|\__,_|_|\__|\__, |              |
#   |                                                  |___/               |
#   '----------------------------------------------------------------------'

wut_webtherm_humidity_defaultlevels = (35, 40, 60, 65)


def inventory_wut_webtherm_humidity(parsed):
    return [
        (sensor_id, "wut_webtherm_humidity_defaultlevels")
        for sensor_id, values in parsed.items()
        if values["type"] == "humid"
    ]


def check_wut_webtherm_humidity(item, params, parsed):
    if item in parsed:
        return check_humidity(parsed[item]["reading"], params)


check_info["wut_webtherm.humidity"] = {
    "inventory_function": inventory_wut_webtherm_humidity,
    "check_function": check_wut_webtherm_humidity,
    "service_description": "Humidity %s",
    "has_perfdata": True,
    "group": "humidity",
}

# .
