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

# Example output:
# <<<mssql_connections>>>
# MSSQLSERVER master 16
# MSSQLSERVER tempdb 1

factory_settings["mssql_connections_default_levels"] = {
    "levels": (None, None),
}


def parse_mssql_connections(info):
    parsed = {}
    for line in info:
        try:
            instance, db_name, connection_count = line
            connection_count = int(connection_count)
            parsed.setdefault("%s %s" % (instance, db_name), connection_count)
        except ValueError:
            pass
    return parsed


def inventory_mssql_connections(parsed):
    for item in parsed:
        yield item, {}


def check_mssql_connections(item, params, parsed):
    # If a database is missing in the agent output there are no
    # active connections for that database.
    return check_levels(
        parsed.get(item, 0),
        "connections",
        params["levels"],
        human_readable_func=int,
        infoname="Connections",
    )


check_info["mssql_connections"] = {
    "parse_function": parse_mssql_connections,
    "inventory_function": inventory_mssql_connections,
    "check_function": check_mssql_connections,
    "service_description": "MSSQL Connections %s",
    "group": "mssql_connections",
    "default_levels_variable": "mssql_connections_default_levels",
    "has_perfdata": True,
}
