# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging
import os
import sys
import warnings

from cliff import app
from cliff import commandmanager

from keystoneauth1 import adapter
from keystoneauth1 import exceptions
from keystoneauth1 import loading

from gnocchiclient import auth
from gnocchiclient import benchmark
from gnocchiclient import client
from gnocchiclient.v1 import aggregates_cli
from gnocchiclient.v1 import archive_policy_cli
from gnocchiclient.v1 import archive_policy_rule_cli as ap_rule_cli
from gnocchiclient.v1 import build_cli
from gnocchiclient.v1 import capabilities_cli
from gnocchiclient.v1 import metric_cli
from gnocchiclient.v1 import resource_cli
from gnocchiclient.v1 import resource_type_cli
from gnocchiclient.v1 import status_cli
from gnocchiclient.version import __version__


class GnocchiCommandManager(commandmanager.CommandManager):
    SHELL_COMMANDS = {
        "status": status_cli.CliStatusShow,
        "server version": build_cli.CliBuildShow,
        "resource list": resource_cli.CliResourceList,
        "resource show": resource_cli.CliResourceShow,
        "resource history": resource_cli.CliResourceHistory,
        "resource search": resource_cli.CliResourceSearch,
        "resource create": resource_cli.CliResourceCreate,
        "resource update": resource_cli.CliResourceUpdate,
        "resource delete": resource_cli.CliResourceDelete,
        "resource batch delete": resource_cli.CliResourceBatchDelete,
        "resource-type list": resource_type_cli.CliResourceTypeList,
        "resource-type create": resource_type_cli.CliResourceTypeCreate,
        "resource-type update": resource_type_cli.CliResourceTypeUpdate,
        "resource-type show": resource_type_cli.CliResourceTypeShow,
        "resource-type delete": resource_type_cli.CliResourceTypeDelete,
        "archive-policy list": archive_policy_cli.CliArchivePolicyList,
        "archive-policy show": archive_policy_cli.CliArchivePolicyShow,
        "archive-policy create": archive_policy_cli.CliArchivePolicyCreate,
        "archive-policy update": archive_policy_cli.CliArchivePolicyUpdate,
        "archive-policy delete": archive_policy_cli.CliArchivePolicyDelete,
        "archive-policy-rule list": ap_rule_cli.CliArchivePolicyRuleList,
        "archive-policy-rule show": ap_rule_cli.CliArchivePolicyRuleShow,
        "archive-policy-rule create": ap_rule_cli.CliArchivePolicyRuleCreate,
        "archive-policy-rule update": ap_rule_cli.CliArchivePolicyRuleUpdate,
        "archive-policy-rule delete": ap_rule_cli.CliArchivePolicyRuleDelete,
        "metric list": metric_cli.CliMetricList,
        "metric show": metric_cli.CliMetricShow,
        "metric create": metric_cli.CliMetricCreate,
        "metric delete": metric_cli.CliMetricDelete,
        "measures show": metric_cli.CliMeasuresShow,
        "measures add": metric_cli.CliMeasuresAdd,
        "measures batch-metrics": metric_cli.CliMetricsMeasuresBatch,
        "measures batch-resources-metrics":
            metric_cli.CliResourcesMetricsMeasuresBatch,
        "measures aggregation": metric_cli.CliMeasuresAggregation,
        "aggregates": aggregates_cli.CliAggregates,
        "capabilities list": capabilities_cli.CliCapabilitiesList,
        "benchmark metric create": benchmark.CliBenchmarkMetricCreate,
        "benchmark metric show": benchmark.CliBenchmarkMetricShow,
        "benchmark measures add": benchmark.CliBenchmarkMeasuresAdd,
        "benchmark measures show": benchmark.CliBenchmarkMeasuresShow,
    }

    def load_commands(self, namespace):
        for name, command_class in self.SHELL_COMMANDS.items():
            self.add_command(name, command_class)


class GnocchiShell(app.App):
    def __init__(self):
        super(GnocchiShell, self).__init__(
            description='Gnocchi command line client',
            version=__version__,
            command_manager=GnocchiCommandManager('gnocchiclient'),
            deferred_help=True,
        )

        self._client = None

    def build_option_parser(self, description, version):
        """Return an argparse option parser for this application.

        Subclasses may override this method to extend
        the parser with more global options.

        :param description: full description of the application
        :paramtype description: str
        :param version: version number for the application
        :paramtype version: str
        """
        parser = super(GnocchiShell, self).build_option_parser(
            description,
            version,
            argparse_kwargs={'allow_abbrev': False})
        parser.add_argument(
            '--gnocchi-api-version',
            default=os.environ.get('GNOCCHI_API_VERSION', '1'),
            help='Defaults to env[GNOCCHI_API_VERSION] or 1.')

        # NOTE(jd) This is a workaroun for people using Keystone auth with the
        # CLI. A lot of rc files do not export OS_AUTH_TYPE=password and
        # assumes it is the default. It's not in that case, but since we can't
        # fix all the rc files of the world, workaround it here.
        if ("OS_PASSWORD" in os.environ and
           "OS_AUTH_TYPE" not in os.environ):
            os.environ.set("OS_AUTH_TYPE", "password")

        loading.register_session_argparse_arguments(parser=parser)
        plugin = loading.register_auth_argparse_arguments(
            parser=parser, argv=sys.argv, default="gnocchi-basic")

        if not isinstance(plugin, (auth.GnocchiNoAuthLoader,
                                   auth.GnocchiBasicLoader)):
            adapter.register_adapter_argparse_arguments(
                parser=parser, service_type="metric")
            adapter.register_service_adapter_argparse_arguments(
                parser=parser, service_type="metric")

            parser.add_argument(
                '--endpoint',
                default=os.environ.get('GNOCCHI_ENDPOINT'),
                help='Gnocchi endpoint (Env: GNOCCHI_ENDPOINT). '
                'Deprecated, use --os-endpoint-override and '
                'OS_ENDPOINT_OVERRIDE instead')

        return parser

    @property
    def client(self):
        # NOTE(sileht): we lazy load the client to not
        # load/connect auth stuffs
        if self._client is None:
            auth_plugin = loading.load_auth_from_argparse_arguments(
                self.options)
            session = loading.load_session_from_argparse_arguments(
                self.options, auth=auth_plugin)

            if isinstance(auth_plugin, (auth.GnocchiNoAuthPlugin,
                                        auth.GnocchiBasicPlugin)):
                # Normal endpoint
                kwargs = dict(
                    version=self.options.gnocchi_api_version,
                    session=session,
                )
            else:
                # Openstck style endpoint
                kwargs = dict(
                    version=(self.options.os_metric_api_version or
                             self.options.os_api_version or
                             self.options.gnocchi_api_version),
                    session=session,
                    adapter_options=dict(
                        service_type=(self.options.os_metric_service_type or
                                      self.options.os_service_type),
                        service_name=(self.options.os_metric_service_name or
                                      self.options.os_service_name),
                        interface=(self.options.os_metric_interface or
                                   self.options.os_interface),
                        region_name=self.options.os_region_name,
                        endpoint_override=(
                            self.options.os_metric_endpoint_override or
                            self.options.os_endpoint_override or
                            self.options.endpoint),
                    )
                )
            self._client = client.Client(**kwargs)
        return self._client

    def clean_up(self, cmd, result, err):
        if err and isinstance(err, exceptions.HttpError):
            try:
                error = err.response.json()
            except Exception:
                pass
            else:
                if 'description' in error:
                    # Gnocchi format
                    print(error['description'])
                elif 'error' in error and 'message' in error['error']:
                    # Keystone format
                    print(error['error']['message'])

    def configure_logging(self):
        if self.options.debug:
            # --debug forces verbose_level 3
            # Set this here so cliff.app.configure_logging() can work
            self.options.verbose_level = 3

        super(GnocchiShell, self).configure_logging()
        root_logger = logging.getLogger('')

        # Set logging to the requested level
        if self.options.verbose_level == 0:
            # --quiet
            root_logger.setLevel(logging.ERROR)
            warnings.simplefilter("ignore")
        elif self.options.verbose_level == 1:
            # This is the default case, no --debug, --verbose or --quiet
            root_logger.setLevel(logging.WARNING)
            warnings.simplefilter("ignore")
        elif self.options.verbose_level == 2:
            # One --verbose
            root_logger.setLevel(logging.INFO)
            warnings.simplefilter("once")
        elif self.options.verbose_level >= 3:
            # Two or more --verbose
            root_logger.setLevel(logging.DEBUG)

        # Hide some useless message
        requests_log = logging.getLogger("requests")
        cliff_log = logging.getLogger('cliff')
        stevedore_log = logging.getLogger('stevedore')
        iso8601_log = logging.getLogger("iso8601")

        cliff_log.setLevel(logging.ERROR)
        stevedore_log.setLevel(logging.ERROR)
        iso8601_log.setLevel(logging.ERROR)

        if self.options.debug:
            requests_log.setLevel(logging.DEBUG)
        else:
            requests_log.setLevel(logging.ERROR)


def main(args=None):
    if args is None:
        args = sys.argv[1:]
    return GnocchiShell().run(args)
