#!/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 json
from typing import Any, Mapping, Optional, Sequence, Union

# TODO: Cleanup this separation violation. This should be accessed through the check API
from cmk.base.config import SpecialAgentConfiguration


def agent_azure_arguments(
    params: Mapping[str, Any],
    hostname: str,
    ipaddress: Optional[str],
) -> Union[SpecialAgentConfiguration, Sequence[str]]:
    secrets = {
        "secret": params["secret"],
    }
    args = []

    keys = ("subscription", "tenant", "client", "piggyback_vms", "sequential")

    for key in (k for k in keys if k in params):
        option = "--%s" % key
        value = params[key]
        if isinstance(value, bool):
            if value:
                args.append(option)
        else:
            args += [option, value]

    config = params["config"]
    if "fetchall" in config:
        return args

    explicit = config.get("explicit", [])
    if explicit:
        args.append("--explicit-config")
    for group_dict in explicit:
        group_name = group_dict["group_name"]
        args.append("group=%s" % group_name)

        group_resources = group_dict.get("resources")
        if group_resources:
            args.append("resources=%s" % ",".join(group_resources))

    tag_based = config.get("tag_based", [])
    for tag, requirement in tag_based:
        if requirement == "exists":
            args += ["--require-tag", tag]
        elif isinstance(requirement, tuple) and requirement[0] == "value":
            args += ["--require-tag-value", tag, requirement[1]]

    return SpecialAgentConfiguration(args, json.dumps(secrets))


special_agent_info["azure"] = agent_azure_arguments
