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

factory_settings["levels_azure_storageaccounts"] = {}
# metrics description:
# https://docs.microsoft.com/en-US/azure/monitoring-and-diagnostics/monitoring-supported-metrics#microsoftstoragestorageaccounts
# 'ingress_levels': tuple [B]
# 'egress_levels': tuple [B]
# 'used_capacity_levels': tuple [B]
# 'server_latency_levels': tuple [ms]
# 'e2e_latency_levels': tuple [ms]
# 'transactions_levels': tuple int
# 'availablility_levels': tuple float
#     The percentage of availability for the storage service or the specified API operation.
#     Availability is calculated by taking the TotalBillableRequests value and dividing it
#     by the number of applicable requests, including those that produced unexpected errors.
#     All unexpected errors result in reduced availability for the storage service or the
#     specified API operation.


@get_data_or_go_stale
def check_azure_storageaccounts(_item, params, resource):
    iter_attrs = azure_iter_informative_attrs(resource, include_keys=("kind", "location"))
    # kind first
    try:
        yield 0, "%s: %s" % next(iter_attrs)
    except StopIteration:
        pass

    levels = params.get("used_capacity_levels", (None, None))
    mcheck = check_azure_metric(
        resource, "total_UsedCapacity", "used_space", "Used capacity", levels=levels
    )
    if mcheck:
        yield mcheck

    for kv_pair in iter_attrs:
        yield 0, "%s: %s" % kv_pair


check_info["azure_storageaccounts"] = {
    "parse_function": parse_azure,
    "inventory_function": discover(),
    "check_function": check_azure_storageaccounts,
    "service_description": "Storage %s account",
    "has_perfdata": True,
    "default_levels_variable": "levels_azure_storageaccounts",
    "group": "azure_storageaccounts",
}


@get_data_or_go_stale
def check_azure_storageaccounts_flow(_item, params, resource):
    for metric_key in ("total_Ingress", "total_Egress", "total_Transactions"):
        cmk_key = metric_key[6:].lower()
        displ = cmk_key.title()
        levels = params.get("%s_levels" % cmk_key, (None, None))
        mcheck = check_azure_metric(resource, metric_key, cmk_key, displ, levels=levels)
        if mcheck:
            yield mcheck


check_info["azure_storageaccounts.flow"] = {
    "inventory_function": discover_azure_by_metrics(
        "total_Ingress", "total_Egress", "total_Transactions"
    ),
    "check_function": check_azure_storageaccounts_flow,
    "service_description": "Storage %s flow",
    "has_perfdata": True,
    "default_levels_variable": "levels_azure_storageaccounts",
    "group": "azure_storageaccounts",
}


@get_data_or_go_stale
def check_azure_storageaccounts_performance(_item, params, resource):

    for key, cmk_key, displ in (
        ("average_SuccessServerLatency", "server_latency", "Success server latency"),
        ("average_SuccessE2ELatency", "e2e_latency", "End-to-end server latency"),
        ("average_Availability", "availability", "Availability"),
    ):
        levels = params.get("%s_levels" % cmk_key, (None, None))
        mcheck = check_azure_metric(resource, key, cmk_key, displ, levels=levels)
        if mcheck:
            yield mcheck


check_info["azure_storageaccounts.performance"] = {
    "inventory_function": discover_azure_by_metrics(
        "average_SuccessServerLatency", "average_SuccessE2ELatency", "average_Availability"
    ),
    "check_function": check_azure_storageaccounts_performance,
    "service_description": "Storage %s performance",
    "has_perfdata": True,
    "default_levels_variable": "levels_azure_storageaccounts",
    "group": "azure_storageaccounts",
}
