#!/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.diskstat import *  # pylint: disable=wildcard-import,unused-wildcard-import

# 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.ucd_hr import *  # pylint: disable=wildcard-import,unused-wildcard-import


def parse_ucd_diskio(info):
    if not info:
        return {}

    parsed = {}
    for line in info:
        if len(line) != 6:
            continue

        index, name, read_size, write_size, read, write = line
        try:
            parsed[name] = {
                "index": index,
                "read_throughput": int(read_size),
                "write_throughput": int(write_size),
                "read_ios": int(read),
                "write_ios": int(write),
            }
        except ValueError:
            pass
    return parsed


@get_parsed_item_data
def check_ucd_diskio(item, params, entry):
    now = time.time()
    disk_data = {}
    for key in ["read_ios", "write_ios", "read_throughput", "write_throughput"]:
        value = entry.get(key)
        if value is None:
            continue
        disk_data[key] = get_rate("ucd_disk_io_%s.%s" % (key, item), now, value)

    yield 0, "[%s]" % entry["index"]

    for state, infotext, perfdata in check_diskstat_dict(item, params, {item: disk_data}):
        yield state, infotext, perfdata


check_info["ucd_diskio"] = {
    "inventory_function": discover(),
    "parse_function": parse_ucd_diskio,
    "check_function": check_ucd_diskio,
    "service_description": "Disk IO %s",
    "snmp_info": (
        ".1.3.6.1.4.1.2021.13.15.1.1",
        [
            "1",  # diskIOIndex
            "2",  # diskIODevice
            "3",  # diskIONRead
            "4",  # diskIONWritten
            "5",  # diskIOReads
            "6",  # diskIOWrites
        ],
    ),
    "snmp_scan_function": is_ucd,
    "has_perfdata": True,
    "group": "diskstat",
}
