# coding=utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4

#
#    Copyright (c) 2012, Intel Performance Learning Solutions Ltd.
#
#    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.

"""
The compute resource backend for OpenStack.
"""

#pylint: disable=W0232,R0201
import random
from occi import backend
from occi import exceptions

from occi_os_api.extensions import os_addon
from occi_os_api.nova_glue import vm
from occi_os_api.nova_glue import security


class OsComputeBackend(backend.MixinBackend, backend.ActionBackend):
    """
    The OpenStackCompute backend.
    """

    def retrieve(self, entity, extras):
        """
        Add OpenStack related actions.
        """
        uid = entity.attributes['occi.core.id']
        context = extras['nova_ctx']

        # set additional actions
        if 'occi.compute.state' in entity.attributes and entity.attributes[
                'occi.compute.state'] == 'active':
            entity.actions.append(os_addon.OS_CREATE_IMAGE)
            entity.actions.append(os_addon.OS_CHG_PWD)

        # add VNC link if available
        console = vm.get_vnc(uid, context)
        if console:
            entity.attributes['org.openstack.compute.console.vnc'] =\
                console['url']
        else:
            entity.attributes['org.openstack.compute.console.vnc'] = 'N/A'

        # also expose the exact openstack state
        entity.attributes['org.openstack.compute.state'] = \
            vm.get_vm(uid, context)['vm_state']

    def action(self, entity, action, attributes, extras):
        """
        This is called by pyssf when an action request is issued.
        """
        context = extras['nova_ctx']