#!/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.mem import *  # pylint: disable=wildcard-import,unused-wildcard-import
# FIXME
# The WATO group 'memory_simple' needs an item and the service_description should
# have a '%s'.  At the moment the current empty item '' and 'Memory' without '%s'
# works but is not consistent.  This will be fixed in the future.
# If we change this we loose history and parameter sets have to be adapted.

# Author: Lars Michelsen <lm@mathias-kettner.de>

# Relevant SNMP OIDs:
# hpLocalMemTotalBytes   1.3.6.1.4.1.11.2.14.11.5.1.1.2.1.1.1.5
# hpLocalMemFreeBytes    1.3.6.1.4.1.11.2.14.11.5.1.1.2.1.1.1.6
# hpLocalMemAllocBytes   1.3.6.1.4.1.11.2.14.11.5.1.1.2.1.1.1.7

factory_settings["hp_procurve_mem_default_levels"] = {"levels": ("perc_used", (80.0, 90.0))}


def inventory_hp_procurve_mem(info):
    if len(info) == 1 and int(info[0][0]) >= 0:
        return [("", 'hp_procurve_mem_default_levels')]


def check_hp_procurve_mem(item, params, info):
    if len(info) != 1:
        return

    if isinstance(params, tuple):
        params = {"levels": ("perc_used", params)}
    mem_total, mem_used = [int(mem) for mem in info[0]]
    return check_memory_element(
        "Usage",
        mem_used,
        mem_total,
        params.get("levels"),
        metric_name="mem_used",
    )


check_info["hp_procurve_mem"] = {
    'check_function': check_hp_procurve_mem,
    'inventory_function': inventory_hp_procurve_mem,
    'service_description': 'Memory',
    'group': 'memory_simple',
    'default_levels_variable': 'hp_procurve_mem_default_levels',
    'has_perfdata': True,
    'snmp_info': ('.1.3.6.1.4.1.11.2.14.11.5.1.1.2.1.1.1', ['5', '7']),
    'snmp_scan_function': lambda oid: ".11.2.3.7.11" in oid(".1.3.6.1.2.1.1.2.0") or ".11.2.3.7.8"
                          in oid(".1.3.6.1.2.1.1.2.0"),
}
