#!/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.cpu_util import *  # pylint: disable=wildcard-import,unused-wildcard-import
# <<<elasticsearch_nodes>>>
# mynode1 open_file_descriptors 434
# mynode1 max_file_descriptors 4096
# mynode1 cpu_percent 0
# mynode1 cpu_total_in_millis 167010
# mynode1 mem_total_virtual_in_bytes 7126290432
# mynode2 open_file_descriptors 430
# mynode2 max_file_descriptors 4096
# mynode2 cpu_percent 0
# mynode2 cpu_total_in_millis 151810
# mynode2 mem_total_virtual_in_bytes 7107313664

nodes_info = {
    'open_file_descriptors': 'Open file descriptors',
    'max_file_descriptors': 'Max file descriptors',
    'cpu_percent': 'CPU used',
    'cpu_total_in_millis': 'CPU total in ms',
    'mem_total_virtual_in_bytes': 'Total virtual memory'
}


def parse_elasticsearch_nodes(info):
    parsed = {}

    for name, desc, value_str in info:
        try:
            if desc == 'cpu_percent':
                value = float(value_str)
            else:
                value = int(value_str)

            parsed.setdefault(name, {}).setdefault(desc, (value, nodes_info[desc]))

        except (IndexError, ValueError):
            pass

    return parsed


factory_settings["elasticsearch_nodes"] = {"cpu_levels": (75.0, 90.0)}


@get_parsed_item_data
def check_elasticsearch_nodes(item, params, item_data):
    for key, hr_func in [
        ('cpu_percent', get_percent_human_readable),
        ('cpu_total_in_millis', int),
        ('mem_total_virtual_in_bytes', get_bytes_human_readable),
        ('open_file_descriptors', int),
        ('max_file_descriptors', int),
    ]:
        value, infotext = item_data[key]

        yield check_levels(value,
                           key,
                           params.get(key),
                           human_readable_func=hr_func,
                           infoname=infotext)


check_info["elasticsearch_nodes"] = {
    "parse_function": parse_elasticsearch_nodes,
    "check_function": check_elasticsearch_nodes,
    "inventory_function": discover(),
    "default_levels_variable": "elasticsearch_nodes",
    "service_description": "Elasticsearch Node %s",
    "has_perfdata": True,
    "group": "elasticsearch_nodes",
}
