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


from typing import NamedTuple, Optional, Sequence

from cmk.base.api.agent_based.type_defs import StringTable


class FortigateCluster(NamedTuple):
    name: str
    status: Optional[str]


FortigateClusterSection = Sequence[FortigateCluster]


def parse_fortigate_sync_status(string_table: StringTable) -> FortigateClusterSection:
    if not string_table:
        return []

    return [
        FortigateCluster(
            name=name,
            status=status if status else None,
        )
        for name, status in string_table
    ]


check_info["fortigate_sync_status"] = {
    "parse_function": parse_fortigate_sync_status,
    "snmp_scan_function": lambda oid: (
        oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.4.1.12356.101.1")
        and oid(".1.3.6.1.4.1.12356.101.13.2.1.1.12.1") is not None
    ),
    "snmp_info": (
        ".1.3.6.1.4.1.12356.101.13.2.1.1",
        ["11", "12"],
    ),  # fgHaStatsHostname, fgHaStatsSyncStatus
}


def discover_fortigate_sync_status(section: FortigateClusterSection):
    if section and len(section) > 1:
        yield (None, None)


def check_fortigate_sync_status(
    _no_item,
    _no_params,
    section: FortigateClusterSection,
):
    map_statuses = {"0": (2, "unsynchronized"), "1": (0, "synchronized")}
    if not section:
        return

    for cluster in section:
        if not cluster.status:
            yield (3, f"{cluster.name}: Status not available")
            return

        status, status_readable = map_statuses.get(
            cluster.status, (3, f"Unknown status {cluster.status}")
        )
        yield status, f"{cluster.name}: {status_readable}"


check_info["fortigate_sync_status"].update(
    {
        "check_function": check_fortigate_sync_status,
        "inventory_function": discover_fortigate_sync_status,
        "service_description": "Sync Status",
    }
)
