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

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

# With reference to SQL sample output (see internal ticket SUP-253)
sap_hana_ess_migration_state_map = {
    "Done (error)": {"cmk_state": 2, "state_readable": "Done with errors."},
    "Installing": {"cmk_state": 1, "state_readable": "Installation in progress."},
    "Done (okay)": {"cmk_state": 0, "state_readable": "Done without errors."},
}


def parse_sap_hana_ess_migration(info):

    parsed = {}
    for sid_instance, lines in sap_hana.parse_sap_hana(info).items():

        if not lines:
            parsed[sid_instance] = {"log": "", "timestamp": "not available"}
            continue

        parsed.setdefault(sid_instance, {"log": " ".join(lines[0]), "timestamp": "not available"})

        for idx, elem in enumerate(lines[0]):
            try:
                timestamp = datetime.datetime.strptime(
                    elem + lines[0][idx + 1], "%Y-%m-%d%H:%M:%S.%f0"
                )
                timestamp = datetime.datetime.strftime(timestamp, "%Y-%m-%d %H:%M:%S")
                parsed[sid_instance]["timestamp"] = timestamp
            except (ValueError, IndexError):
                pass

    return parsed


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


@get_parsed_item_data
def check_sap_hana_ess_migration(item, params, data):

    if not data or "log" not in data or not data["log"]:
        raise MKCounterWrapped("Login into database failed.")

    key = None
    for ident in sap_hana_ess_migration_state_map.keys():
        if ident.lower() in data["log"].lower():
            key = ident

    states = sap_hana_ess_migration_state_map.get(
        key, {"cmk_state": 3, "state_readable": "Unknown [%s]" % data["log"]}
    )
    infotext = "ESS State: %s Timestamp: %s" % (states["state_readable"], data["timestamp"])
    return states["cmk_state"], infotext


check_info["sap_hana_ess_migration"] = {
    "parse_function": parse_sap_hana_ess_migration,
    "inventory_function": inventory_sap_hana_ess_migration,
    "check_function": check_sap_hana_ess_migration,
    "service_description": "SAP HANA ESS Migration %s",
}
