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

# <<<splunk_license_usage>>>
# 524288000 5669830

SplunkLicenseUsage = collections.namedtuple(  # pylint: disable=collections-namedtuple-call
    "lcsusg", ["quota", "slaves_usage_bytes"]
)


def parse_splunk_license_usage(info):
    parsed = {}

    for lcs_detail in info:
        try:
            quota, slaves_usage_bytes = lcs_detail

            parsed.setdefault("License Usage", []).append(
                SplunkLicenseUsage(int(quota), int(slaves_usage_bytes))
            )

        except (IndexError, ValueError):
            pass

    return parsed


factory_settings["splunk_license_usage_default_levels"] = {
    "usage_bytes": (80.0, 90.0),
}


def inventory_splunk_license_usage(parsed):
    yield None, {}


def check_splunk_license_usage(item, params, parsed):
    data = parsed["License Usage"][0]

    yield 0, "Quota: %s" % get_bytes_human_readable(data.quota)

    warn, crit = params["usage_bytes"]

    for value, infotext in [(data.slaves_usage_bytes, "Slaves usage")]:
        if isinstance(warn, float):
            warn = data.quota / 100 * warn
            crit = data.quota / 100 * crit

        yield check_levels(
            value,
            "splunk_slave_usage_bytes",
            (warn, crit),
            human_readable_func=get_bytes_human_readable,
            infoname=infotext,
        )


check_info["splunk_license_usage"] = {
    "parse_function": parse_splunk_license_usage,
    "check_function": check_splunk_license_usage,
    "inventory_function": inventory_splunk_license_usage,
    "service_description": "Splunk License Usage",
    "group": "splunk_license_usage",
    "default_levels_variable": "splunk_license_usage_default_levels",
    "has_perfdata": True,
}
