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

# <<<oracle_instance:sep(124)>>>
# XE|11.2.0.2.0|OPEN|ALLOWED|STOPPED|3524|2752243048|NOARCHIVELOG|PRIMARY|NO|XE|080220151025
# last entry: db creation time 'ddmmyyyyhh24mi'


def _parse_raw_db_creation_time(raw_db_creation_time):
    if raw_db_creation_time is None:
        return None

    # We just translate the format to another
    # "%d%m%Y%H%M%S" => "%Y-%m-%d %H:%M"
    # we cannot use time because we have no information about the timezone here.
    try:
        year = int(raw_db_creation_time[4:8])
        month = int(raw_db_creation_time[2:4])
        day = int(raw_db_creation_time[:2])
        hours = int(raw_db_creation_time[8:10])
        minutes = int(raw_db_creation_time[10:])
    except (IndexError, ValueError):
        return None
    return "%s-%02d-%02d %02d:%02d" % (year, month, day, hours, minutes)


def inv_oracle_instance(info, inventory_tree, status_data_tree):
    path = "software.applications.oracle.instance:"
    inv_node = inventory_tree.get_list(path)
    status_node = status_data_tree.get_list(path)
    for item_data in sorted(info.values(), key=lambda v: v.get("sid")):
        if item_data['invalid_data']:
            continue

        inv_node.append({
            "sid": item_data['sid'],
            "pname": item_data['pname'],
            "version": item_data['version'],
            "openmode": item_data['openmode'],
            "logmode": item_data['log_mode'],
            "logins": item_data['logins'],
            "db_creation_time": _parse_raw_db_creation_time(item_data['db_creation_time']),
        })

        try:
            up_seconds = int(item_data['up_seconds'])
        except (TypeError, ValueError):
            up_seconds = None

        status_node.append({
            "sid": item_data['sid'],
            "pname": item_data['pname'],
            "db_uptime": up_seconds,
        })


inv_info['oracle_instance'] = {
    'inv_function': inv_oracle_instance,
}
