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


def parse_casa_cpu_mem(info):
    entity_names = {int(k): v for k, v in (x for x in info[0])}
    data = {}
    for idx, entry in enumerate(info[1]):
        entry_nr = int(entry[0])
        data[entity_names[entry_nr]] = {
            "mem_total": int(info[1][idx][1]),
            "mem_used": int(info[2][idx][1]),
        }
    return data


def inventory_casa_cpu_mem(parsed):
    inventory = []
    for k, v in parsed.items():
        if v.get("mem_total"):
            inventory.append((k, {}))
    return inventory


@get_parsed_item_data
def check_casa_cpu_mem(item, params, data):
    warn, crit = params.get("levels", (None, None))
    mode = "abs_used" if isinstance(warn, int) else "perc_used"
    return check_memory_element(
        "Usage",
        data["mem_used"],
        data["mem_total"],
        (mode, (warn, crit)),
        metric_name="memused",
    )


check_info["casa_cpu_mem"] = {
    "parse_function": parse_casa_cpu_mem,
    "inventory_function": inventory_casa_cpu_mem,
    "check_function": check_casa_cpu_mem,
    "service_description": "Memory %s",
    "has_perfdata": True,
    "group": "memory_multiitem",
    "snmp_scan_function": lambda oid: oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.4.1.20858.2."),
    "snmp_info": [
        (".1.3.6.1.2.1.47.1.1.1.1.2", [OID_END, ""]),  # Entity descriptions, quite long...
        (".1.3.6.1.4.1.20858.10.13.1.1.1.1", [OID_END, ""]),  # Total mem
        (".1.3.6.1.4.1.20858.10.13.1.1.1.2", [OID_END, ""]),  # Total allocated mem
        (".1.3.6.1.4.1.20858.10.36.1.1.1.1", [OID_END, ""]),  # Installed slot
    ],
}
