# vim: tabstop=4 shiftwidth=4 softtabstop=4

# 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.

"""Config Drive extension."""

from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil

ALIAS = "os-config-drive"
ATTRIBUTE_NAME = "%s:config_drive" % ALIAS
authorize = extensions.soft_extension_authorizer('compute', 'v3:' + ALIAS)


class ServerConfigDriveTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('server')
        root.set('{%s}config_drive' % ConfigDrive.namespace, ATTRIBUTE_NAME)
        return xmlutil.SlaveTemplate(root, 1, nsmap={ConfigDrive.alias:
                                                     ConfigDrive.namespace})


class ServersConfigDriveTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('servers')
        elem = xmlutil.SubTemplateElement(root, 'server', selector='servers')
        elem.set('{%s}config_drive' % ConfigDrive.namespace, ATTRIBUTE_NAME)
        return xmlutil.SlaveTemplate(root, 1, nsmap={ConfigDrive.alias:
                                                     ConfigDrive.namespace})


class ConfigDriveController(wsgi.Controller):

    def _add_config_drive(self, req, servers):
        for server in servers:
            db_server = req.get_db_instance(server['id'])
            # server['id'] is guaranteed to be in the cache due to
            # the core API adding it in its 'show'/'detail' methods.
            server[ATTRIBUTE_NAME] = db_server['config_drive']

    def _show(self, req, resp_obj):
        if 'server' in resp_obj.obj:
            resp_obj.attach(xml=ServerConfigDriveTemplate())
            server = resp_obj.obj['server']
            self._add_config_drive(req, [server])

    @wsgi.extends
    def show(self, req, resp_obj, id):
        context = req.environ['nova.context']
        if authorize(context):
            self._show(req, resp_obj)

    @wsgi.extends
    def detail(self, req, resp_obj):
        context = req.environ['nova.context']
        if 'servers' in resp_obj.obj and authorize(context):
            resp_obj.attach(xml=ServersConfigDriveTemplate())
            servers = resp_obj.obj['servers']
            self._add_config_drive(req, servers)


class ConfigDrive(extensions.V3APIExtensionBase):
    """Config Drive Extension."""

    name = "ConfigDrive"
    alias = ALIAS
    namespace = "http://docs.openstack.org/compute/ext/config_drive/api/v3"
    version = 1

    def get_controller_extensions(self):
        controller = ConfigDriveController()
        extension = extensions.ControllerExtension(self, 'servers', controller)
        return [extension]

    def get_resources(self):
        return []

    def server_create(self, server_dict, create_kwargs):
        create_kwargs['config_drive'] = server_dict.get(ATTRIBUTE_NAME)

    def server_xml_extract_server_deserialize(self, server_node, server_dict):
        config_drive = server_node.getAttribute(ATTRIBUTE_NAME)
        if config_drive:
            server_dict[ATTRIBUTE_NAME] = config_drive
