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


# TODO unify with other if inventory plugins
def inv_winperf_if(parsed, params, inventory_tree):
    _agent_timestamp, perf, _dhcp = parsed
    usage_port_types = params.get(
        "usage_port_types",
        ['6', '32', '62', '117', '127', '128', '129', '180', '181', '182', '205', '229'])

    def render_mac_address(bytestring):
        return ":".join(["%02s" % hex(ord(m))[2:] for m in bytestring]).replace(' ', '0').upper()

    interfaces = []
    total_ethernet_ports = 0
    available_ethernet_ports = 0
    for interface in perf:

        if interface.type in ("231", "232") or not interface.speed:
            continue  # Useless entries for "TenGigabitEthernet2/1/21--Uncontrolled"
            # Ignore useless half-empty tables (e.g. Viprinet-Router)

        if_info = {
            "index": int(interface.index[-1]),
            "description": interface.descr,
            "alias": interface.alias,
            "speed": int(interface.speed),
            "phys_address": render_mac_address(interface.phys_address),
            "oper_status": int(interface.oper_status[0]),
            "port_type": int(interface.type),
        }

        if interface.type in usage_port_types:
            if_available = interface.oper_status == '2'
            total_ethernet_ports += 1
            if if_available:
                available_ethernet_ports += 1
        else:
            if_available = None

        if_info["available"] = if_available
        interfaces.append(if_info)

    node = inventory_tree.get_list("networking.interfaces:")
    node.extend(sorted(interfaces, key=lambda r: r.get('index')))

    node = inventory_tree.get_dict("networking.")
    node["available_ethernet_ports"] = available_ethernet_ports
    node["total_ethernet_ports"] = total_ethernet_ports
    node["total_interfaces"] = len(perf)


inv_info['winperf_if'] = {
    'inv_function': inv_winperf_if,
}
