#!/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.postgres import *  # pylint: disable=wildcard-import,unused-wildcard-import
# <<<postgres_query_duration>>>
# [databases_start]
# postgres
# testdb
# datenbank
# [databases_end]
# datname;datid;usename;client_addr;state;seconds;pid;current_query
# postgres;12068;postgres;;active;0;12631;SELECT datname, datid, usename, ....

# instance
# <<<postgres_query_duration>>>
# [[[foobar]]]
# [databases_start]
# postgres
# testdb
# [databases_end]
# ...


def inventory_postgres_query_duration(parsed):
    for entry in parsed:
        yield entry, {}


def check_postgres_query_duration(item, _no_params, parsed):
    if item not in parsed:
        # 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")

    longest_time = -1
    longest_info = None
    for element in parsed[item]:
        if int(element["seconds"]) > longest_time:
            longest_info = element
            longest_time = int(element["seconds"])

    if longest_info:
        yield 0, "Longest query is %s seconds" % longest_info["seconds"]
        if longest_info["usename"]:
            yield 0, "Username: %s" % longest_info["usename"]
        if longest_info["client_addr"]:
            yield 0, "Client: %s" % longest_info["client_addr"]
        if longest_info["state"].lower() != "active":
            yield 0, "Query state: %s" % longest_info["state"]
        yield 0, "PID: %s, Query: %s" % (longest_info["pid"], longest_info["current_query"])

    else:
        yield 0, "No query is running"


check_info['postgres_query_duration'] = {
    "parse_function": parse_postgres_dbs,
    "check_function": check_postgres_query_duration,
    "inventory_function": inventory_postgres_query_duration,
    "service_description": "PostgreSQL Query Duration %s",
}
