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

import typing

# Example agent output:
# old format
# <<<nullmailer_mailq>>>
# 8 1

# new format
# <<<nullmailer_mailq>>>
# 8 1 deferred
# 8 1 failed

nullmailer_mailq_default_levels = {
    "deferred": (10, 20),
    "failed": (1, 1),
}

factory_settings["nullmailer_mailq_default_levels"] = nullmailer_mailq_default_levels


class Queue(typing.NamedTuple):
    size: int
    length: int
    name: str


def parse_nullmailer_mailq(info):
    def name(line):
        return line[2] if len(line) == 3 else "deferred"

    return [Queue(size=int(line[0]), length=int(line[1]), name=name(line)) for line in info]


def inventory_nullmailer_mailq(parsed):
    if parsed:
        yield "", {}


def _check_single_queue(queue: Queue, levels_length: typing.Tuple[int, int]):
    make_metric = queue.name == "deferred"

    yield check_levels(
        queue.length,
        "length" if make_metric else None,
        levels_length,
        human_readable_func=lambda x: "%d" % x,
        infoname=queue.name.capitalize(),
        unit="mails",
    )

    yield check_levels(
        queue.size,
        "size" if make_metric else None,
        None,
        human_readable_func=get_bytes_human_readable,
        infoname="Size",
    )


def check_nullmailer_mailq(_no_item, params, parsed):
    if not isinstance(params, dict):
        params = {
            "deferred": params,
        }

    for queue in parsed:
        yield from _check_single_queue(queue, params.get(queue.name))


check_info["nullmailer_mailq"] = {
    "parse_function": parse_nullmailer_mailq,
    "check_function": check_nullmailer_mailq,
    "inventory_function": inventory_nullmailer_mailq,
    "service_description": "Nullmailer Queue %s",
    "default_levels_variable": "nullmailer_mailq_default_levels",
    "group": "mail_queue_length",
    "has_perfdata": True,
}
