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

# consideration of health status and port speed availability status quo
discovery_netapp_api_ports_ignored = []


def parse_netapp_ports(info):
    def port_name(name, values):
        try:
            return "%s port %s" % (values["port-type"].capitalize(), name)
        except KeyError:
            return name

    return netapp_api_parse_lines(info, item_func=port_name)


def _identify_ignored_port_types(discovery_ignored):
    return host_extra_conf_merged(host_name(), discovery_ignored).get("ignored_ports", ())


def discovery_netapp_api_port(parsed):
    ignored_ports = _identify_ignored_port_types(discovery_netapp_api_ports_ignored)
    for item, values in parsed.items():
        if values.get("port-type") in ignored_ports:
            continue
        if "health-status" in values:
            yield item, {}


@get_parsed_item_data
def check_netapp_api_port(item, params, data):
    health_state = data.get("health-status", "unknown")
    status = {"healthy": 0, "unknown": 3}.get(health_state, 2)
    yield status, "Health status: %s, Operational speed: %s" % (
        health_state,
        data.get("operational-speed", "undetermined"),
    )


check_info["netapp_api_ports"] = {
    "check_function": check_netapp_api_port,
    "inventory_function": discovery_netapp_api_port,
    "parse_function": parse_netapp_ports,
    "service_description": "%s",
}
