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


def inventory_wmi_cpuload(tables):
    if required_tables_missing(tables, ["computer_system", "system_perf"]):
        return []
    return [(None, None)]


def check_wmi_cpuload(item, params, parsed):
    # the processor queue length is logically similar to linux cpu load as
    # it states the number of processes waiting to be assigned cpu time.
    # unlike cpu load this does not include processes currently being processed,
    # so unless to cpu is (almost) fully utilized, this will be 0.

    try:
        load = int(parsed["system_perf"].get(0, "ProcessorQueueLength"))
        this_time = get_wmi_time(parsed["system_perf"], 0)
        load5min = get_average("load_5min", this_time, load, 5)
        load15min = get_average("load_15min", this_time, load, 15)
        computer_system = parsed["computer_system"]
    except KeyError as e:
        return 3, "Missing information from agent: %s" % e

    try:
        cores = int(computer_system.get(0, "NumberOfLogicalProcessors"))
        processor_type = ProcessorType.logical
    except (ValueError, KeyError, MKGeneralException):
        # NumberOfLogicalProcessors can be an empty string, not sure why
        cores = int(computer_system.get(0, "NumberOfProcessors"))
        processor_type = ProcessorType.physical

    return check_cpu_load_generic(params, (load, load5min, load15min),
                                  num_cpus=cores,
                                  processor_type=processor_type)


check_info['wmi_cpuload'] = {
    'parse_function': parse_wmi_table,
    'inventory_function': inventory_wmi_cpuload,
    'check_function': check_wmi_cpuload,
    'has_perfdata': True,
    'service_description': "Processor Queue",
    'group': 'cpu_load',
}
