#!/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.df import *  # pylint: disable=wildcard-import,unused-wildcard-import
# 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.size_trend import *  # pylint: disable=wildcard-import,unused-wildcard-import
import cmk.base.plugins.agent_based.utils.sap_hana as sap_hana


def parse_sap_hana_diskusage(info):
    parsed = {}
    for sid_instance, lines in sap_hana.parse_sap_hana(info).items():
        for line in lines:
            if len(line) < 3:
                continue
            inst = parsed.setdefault("%s - %s" % (sid_instance, line[0]), {
                "state_name": line[1],
            })
            inst.update(_extract_size_and_used_from_line(line))
    return parsed


def _extract_size_and_used_from_line(line):
    # Values are measured in GB. Are other factors possible? (Query)
    inst_values = {}
    splitted_line = line[-1].split()
    for key, index in [
        ("size", 1),
        ("used", 4),
    ]:
        try:
            inst_values[key] = float(splitted_line[index]) * 1024
        except (ValueError, IndexError):
            pass
    return inst_values


def inventory_sap_hana_diskusage(parsed):
    for item in parsed:
        yield item, {}


@get_parsed_item_data
def check_sap_hana_diskusage(item, params, data):
    state_name = data['state_name']
    if state_name == 'OK':
        state = 0
    elif state_name == "UNKNOWN":
        state = 3
    else:
        state = 2
    yield state, "Status: %s" % state_name

    size_mb = data['size']
    used_mb = data['used']
    avail_mb = size_mb - used_mb
    yield df_check_filesystem_list(item, params, [(item, size_mb, avail_mb, 0)])


check_info['sap_hana_diskusage'] = {
    'parse_function': parse_sap_hana_diskusage,
    'inventory_function': inventory_sap_hana_diskusage,
    'check_function': check_sap_hana_diskusage,
    'service_description': 'SAP HANA Disk %s',
    "has_perfdata": True,
    'group': 'filesystem',
    'default_levels_variable': 'filesystem_default_levels',
}
