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

# <<<oracle_logswitches>>>
# pengt  15
# hirni  22

factory_settings["oracle_logswitches_default_levels"] = {
    "levels": (50, 100),
    "levels_lower": (-1, -1),
}


def inventory_oracle_logswitches(info):
    oracle_handle_ora_errors_discovery(info)
    return [(line[0], {}) for line in info if len(line) == 2]


def check_oracle_logswitches(item, params, info):

    if isinstance(params, tuple):
        params = {
            "levels": (params[2], params[3]),
            "levels_lower": (params[0], params[1]),
        }

    for line in info:
        if line[0] == item:
            err = oracle_handle_ora_errors(line)
            if err is False:
                continue
            elif isinstance(err, tuple):
                return err
            if len(line) != 2:
                continue

            lowarn, locrit = params["levels_lower"]
            warn, crit = params["levels"]
            logswitches = int(line[1])
            infotext = (
                "%d log switches in the last 60 minutes (warn/crit below %d/%d) (warn/crit at %d/%d)"
                % (logswitches, locrit, lowarn, warn, crit)
            )
            perfdata = [("logswitches", logswitches, warn, crit, 0, None)]
            if logswitches >= crit or logswitches <= locrit:
                return (2, infotext, perfdata)
            elif logswitches >= warn or logswitches <= lowarn:
                return (1, infotext, perfdata)
            return (0, infotext, perfdata)

    # In case of missing information we assume that the login into
    # the database has failed and we simply skip this check. It won't
    # switch to UNKNOWN, but will get stale.
    raise MKCounterWrapped("Login into database failed")


check_info["oracle_logswitches"] = {
    "check_function": check_oracle_logswitches,
    "inventory_function": inventory_oracle_logswitches,
    "service_description": "ORA %s Logswitches",
    "has_perfdata": True,
    "group": "oracle_logswitches",
    "default_levels_variable": "oracle_logswitches_default_levels",
}
