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

# <<<db2_connections>>>
# [[[db2taddm:CMDBS1]]]
# port 50214
# sessions 40
# latency 0:1.03

factory_settings["db2_connections_default_levels"] = {
    "levels_total": (150, 200),
}


def inventory_db2_connections(parsed):
    for item in parsed[1]:
        yield item, None


def check_db2_connections(item, params, parsed):
    db = parsed[1].get(item)
    if not db:
        raise MKCounterWrapped("Login into database failed")

    data = dict(db)

    warn, crit = params["levels_total"]
    connections = int(data["connections"])
    state = 0
    if connections >= crit:
        state = 2
    elif connections >= warn:
        state = 1
    yield state, "Connections: %s" % connections, [("connections", connections, warn, crit)]

    yield 0, "Port: %s" % data["port"]

    if "latency" in data:
        latency = data["latency"]
        if ":" not in latency:
            ms = int(latency)
        else:  # handle old time format: 'min:seconds.milliseconds'
            minutes, rest = data["latency"].split(":")
            # handle different locale settings
            if "," in rest:
                seconds, mseconds = rest.split(",")
            else:
                seconds, mseconds = rest.split(".")
            ms = int(minutes) * 60 * 1000 + int(seconds) * 1000 + int(mseconds)

        yield 0, "Latency: %.2f ms" % ms, [("latency", ms)]


check_info["db2_connections"] = {
    "parse_function": parse_db2_dbs,
    "service_description": "DB2 Connections %s",
    "check_function": check_db2_connections,
    "inventory_function": inventory_db2_connections,
    "has_perfdata": True,
    "group": "db2_connections",
    "default_levels_variable": "db2_connections_default_levels",
}
