#!/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.aws import *  # pylint: disable=wildcard-import,unused-wildcard-import


def check_aws_dynamodb_summary(item, params, parsed):

    tables_by_region: Dict[str, Dict] = {}

    for table in parsed:
        tables_by_region.setdefault(AWSRegions[table['Region']], {})[table['TableName']] = table

    regions_sorted = sorted(tables_by_region.keys())
    long_output = []

    yield 0, "Total number of tables: %s" % len(parsed)

    for region in regions_sorted:
        tables_region = tables_by_region[region]
        yield 0, "%s: %s" % (region, len(tables_region))

        tables_names_sorted = sorted(tables_region.keys())
        long_output.append("%s:" % region)

        for table_name in tables_names_sorted:
            table = tables_region[table_name]
            long_output.append(
                "%s -- Items: %s, Size: %s, Status: %s" %
                (table_name, table['ItemCount'], get_bytes_human_readable(
                    table['TableSizeBytes']), table['TableStatus']))

    if long_output:
        yield 0, "\n%s" % "\n".join(long_output)


check_info['aws_dynamodb_summary'] = {
    'parse_function': parse_aws,
    'inventory_function': discover_single,
    'check_function': check_aws_dynamodb_summary,
    'service_description': 'AWS/DynamoDB Summary',
}
