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

#
# 2017 comNET GmbH, Bjoern Mueller


def inventory_kentix_motion(info):
    if info:
        index = info[0][0].split(".", 3)[-1]
        yield index, {}


def check_kentix_motion(item, params, info):
    def test_in_period(time, periods):
        time_mins = time[0] * 60 + time[1]
        for per in periods:
            per_mins_low = per[0][0] * 60 + per[0][1]
            per_mins_high = per[1][0] * 60 + per[1][1]
            if time_mins >= per_mins_low and time_mins < per_mins_high:
                return True
        return False

    for line in info:
        if line[0].split(".", 3)[-1] == item:
            value, valmax = map(int, line[1:3])
            weekdays = [
                "monday",
                "tuesday",
                "wednesday",
                "thursday",
                "friday",
                "saturday",
                "sunday",
            ]
            today = time.localtime()
            if params is not None and "time_periods" in params:
                periods = params["time_periods"][weekdays[today.tm_wday]]
            else:
                periods = [((0, 0), (24, 0))]
            if value >= valmax:
                status = 1 if test_in_period((today.tm_hour, today.tm_min), periods) else 0
                return status, "Motion detected", [("motion", value, valmax, None, 0, 100)]
            return 0, "No motion detected", [("motion", value, valmax, None, 0, 100)]


check_info["kentix_motion"] = {
    "inventory_function": inventory_kentix_motion,
    "check_function": check_kentix_motion,
    "service_description": "Motion Detector %s",
    "has_perfdata": True,
    "group": "motion",
    "snmp_info": (
        ".1.3.6.1.4.1.37954",
        ["2.1.5", "3.1.5"],
        [
            0,  # Numeric index
            "1",  # MotionValue
            "2",  # MotionMax
        ],
    ),
    "snmp_scan_function": lambda oid: oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.4.1.332.11.6"),
}
