#!/usr/bin/env python3
# pylint: disable=missing-module-docstring, unused-argument, missing-function-docstring

from pprint import pprint

from cmk.utils import debug

# import necessary elements from API version 2
from cmk.agent_based.v2 import (
    AgentSection,
    CheckPlugin,
    Service,
    Result,
    State,
)


def parse_hal9002_status(string_table):
    """the parse function"""
    parsed_data = {}
    # we only expect one line with four entries
    line = string_table[0]
    parsed_data["status"] = line[0]
    parsed_data["version"] = line[1]
    parsed_data["username"] = line[2]
    parsed_data["ipaddress"] = line[3]
    return parsed_data


def discover_hal9002_status(section):
    """the discover function"""
    yield Service()


def check_hal9002_status(params, section):
    """the check function"""
    if debug.enabled():
        pprint(section)
    # print(params["state_if_update_is_available"])
    status = section["status"]
    version = section["version"]
    username = section["username"]
    ipaddress = section["ipaddress"]
    # check what status is reported and set state accordingly
    if status == "ok":
        state = State.OK
    elif status == "update available":
        state = params["state_if_update_is_available"]
    elif status == "storage down":
        state = State.CRIT
    else:
        state = State.UNKNOWN
    summary = f'Status is "{status}", Version is "{version}"'
    details = f'User/IP used for access is "{username}/{ipaddress}"'
    # no metrics, just a simple service
    yield Result(state=state, summary=summary, details=details)


# create the new agent section, must begin with "agent_section_"
# and must be an instance of "AgentSection"
agent_section_hal9002_status = AgentSection(
    # "name" must exactly match the section name within the agent output
    name="hal9002_status",
    # define the parse function, name is arbitrary, a good choice is to choose
    # "parse_" as prefix and append the section name
    parse_function=parse_hal9002_status,
)

# create the new check plugin, must begin with "check_plugin_"
#  and must be an instance of "CheckPlugin"
check_plugin_hal9002_status = CheckPlugin(
    # "name" should be the same as the corresponding section within the agent output
    name="hal9002_status",
    service_name="HAL9002 Status",
    # define the discovery function, name is arbitrary, a good choice is to choose
    # "discover_" as prefix and append the section name
    discovery_function=discover_hal9002_status,
    # define the check function, name is arbitrary, a good choice is to choose
    # "check_" as prefix and append the section name
    check_function=check_hal9002_status,
    # define the default parameters
    check_default_parameters={"state_if_update_is_available": State.WARN},
    # connect to the ruleset where parameters can be defined
    # must match the name of the ruleset exactly
    check_ruleset_name="hal9002_status",
)