#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2018             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

AWSCostAndUageMetrics = [
    ("Unblended", "UnblendedCost", "unblended"),
]


def parse_aws_costs_and_usage(info):
    parsed = {}
    for row in parse_aws(info):
        timeperiod = row['TimePeriod']['Start']
        for group in row.get('Groups', []):
            service_name = " ".join(group['Keys'])
            for metric_name, metrics in group['Metrics'].iteritems():
                try:
                    costs = float(metrics['Amount'])
                    unit = metrics['Unit']
                except (KeyError, ValueError):
                    continue
                else:
                    parsed.setdefault((timeperiod, service_name), {})\
                          .setdefault(metric_name, (costs, unit))
    return parsed


#   .--summary-------------------------------------------------------------.
#   |                                                                      |
#   |           ___ _   _ _ __ ___  _ __ ___   __ _ _ __ _   _             |
#   |          / __| | | | '_ ` _ \| '_ ` _ \ / _` | '__| | | |            |
#   |          \__ \ |_| | | | | | | | | | | | (_| | |  | |_| |            |
#   |          |___/\__,_|_| |_| |_|_| |_| |_|\__,_|_|   \__, |            |
#   |                                                    |___/             |
#   +----------------------------------------------------------------------+
#   |                           main check                                 |
#   '----------------------------------------------------------------------'


def inventory_aws_costs_and_usage_summary(parsed):
    if parsed:
        return [("Summary", {})]


def check_aws_costs_and_usage_summary(item, params, parsed):
    amounts_by_metrics = collections.defaultdict(float)
    for (timeperiod, _service_name), metrics in parsed.iteritems():
        for title, metric_name, key, in AWSCostAndUageMetrics:
            costs, unit = metrics[metric_name]
            amounts_by_metrics[(timeperiod, title, unit, key)] += costs

    for (timeperiod, title, unit, key), costs in amounts_by_metrics.iteritems():
        yield check_levels_backport(
            costs,
            "aws_costs_%s" % key,
            params.get('levels_%s' % key, (None, None)),
            infoname="(%s) Total %s %s" % (timeperiod, title, unit))


check_info['aws_costs_and_usage'] = {
    'parse_function': parse_aws_costs_and_usage,
    'inventory_function': inventory_aws_costs_and_usage_summary,
    'check_function': check_aws_costs_and_usage_summary,
    'service_description': 'AWS/CE %s',
    'includes': ['backport.include', 'aws.include'],
    'group': 'aws_costs_and_usage',
    'has_perfdata': True,
}

#.
#   .--per service---------------------------------------------------------.
#   |                                                _                     |
#   |          _ __   ___ _ __   ___  ___ _ ____   _(_) ___ ___            |
#   |         | '_ \ / _ \ '__| / __|/ _ \ '__\ \ / / |/ __/ _ \           |
#   |         | |_) |  __/ |    \__ \  __/ |   \ V /| | (_|  __/           |
#   |         | .__/ \___|_|    |___/\___|_|    \_/ |_|\___\___|           |
#   |         |_|                                                          |
#   '----------------------------------------------------------------------'


def inventory_aws_costs_and_usage_per_service(parsed):
    for (_timeperiod, service_name) in parsed.iterkeys():
        yield service_name, {}


def check_aws_costs_and_usage_per_service(item, params, parsed):
    data = None
    timeperiod = None
    for (timeperiod, service_name), metrics in parsed.iteritems():
        if item == service_name:
            data = metrics
            break
    if not data:
        return

    for title, metric_name, key in AWSCostAndUageMetrics:
        costs, unit = data[metric_name]
        yield check_levels_backport(
            costs,
            "aws_costs_%s" % key,
            params.get('levels_%s' % key, (None, None)),
            infoname="(%s) %s %s" % (timeperiod, title, unit))


check_info['aws_costs_and_usage.per_service'] = {
    'inventory_function': inventory_aws_costs_and_usage_per_service,
    'check_function': check_aws_costs_and_usage_per_service,
    'service_description': 'AWS/CE %s',
    'group': 'aws_costs_and_usage',
    'includes': ['backport.include'],
    'has_perfdata': True,
}
