#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2019 Checkmk 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.

# Example output from agent:
# <<<modbus_value>>>
# 856 1827893 counter active_energy
# 790 11204 gauge active_power

modbus_value_default_levels = (None, None)


def inventory_modbus_value(info):
    return [(x[-1], "modbus_value_default_levels") for x in info]


def check_modbus_value(item, params, info):
    for cid, value, _ctype, name in info:
        if name == item:
            value = saveint(value)
            message_end = ""
            warn, crit = params
            state = 0
            if crit and crit >= value:
                state = 2
                message_end += "(Levels Warning/Critical at %s/%s)"
            if warn and warn >= value:
                state = 1
                message_end += "(Levels Warning/Critical at %s/%s)"
            message = "Current: %.2f %s (%s)" % (value, message_end, cid)
            return state, message, [(name, value, warn, crit)]

    return 3, "Value not found in Agent output"


check_info["modbus_value"] = {
    "check_function": check_modbus_value,
    "inventory_function": inventory_modbus_value,
    "service_description": "Value %s",
    "has_perfdata": True,
    "group": "modbus_value",
}
