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

import cmk.base.plugins.agent_based.utils.sap_hana as sap_hana


def parse_sap_hana_ess(info):
    parsed = {}
    for sid_instance, lines in sap_hana.parse_sap_hana(info).items():
        inst_data = {}
        for line in lines:
            if len(line) < 2:
                continue

            key = line[0]
            if key == "started":
                try:
                    inst_data[key] = int(line[1])
                except ValueError:
                    pass
            else:
                inst_data[key] = line[1]
        if inst_data:
            parsed.setdefault(sid_instance, inst_data)
    return parsed


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


@get_parsed_item_data
def check_sap_hana_ess(item, params, data):
    active_state_name = data['active']
    if active_state_name == 'unknown':
        state = 3
    elif active_state_name in ['false', 'no']:
        state = 2
    else:
        state = 0
    yield state, "Active status: %s" % active_state_name

    started_threads = data.get('started')
    if started_threads is None or started_threads < 1:
        state = 2
    else:
        state = 0
    yield state, 'Started threads: %s' % started_threads, [('threads', started_threads)]


check_info['sap_hana_ess'] = {
    'parse_function': parse_sap_hana_ess,
    'inventory_function': inventory_sap_hana_ess,
    'check_function': check_sap_hana_ess,
    'service_description': 'SAP HANA ESS %s',
    "has_perfdata": True,
}
