# Copyright 2013 Rackspace Hosting
# 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 copy
import uuid

from lxml import etree
from webob import exc

from nova.api.openstack.compute.contrib import instance_actions
from nova.compute import api as compute_api
from nova import db
from nova.db.sqlalchemy import models
from nova import exception
from nova.openstack.common import policy as common_policy
from nova import policy
from nova import test
from nova.tests.api.openstack import fakes
from nova.tests import fake_instance
from nova.tests import fake_server_actions

FAKE_UUID = fake_server_actions.FAKE_UUID
FAKE_REQUEST_ID = fake_server_actions.FAKE_REQUEST_ID1


def format_action(action):
    '''Remove keys that aren't serialized.'''
    to_delete = ('id', 'finish_time', 'created_at', 'updated_at', 'deleted_at',
                 'deleted')
    for key in to_delete:
        if key in action:
            del(action[key])
    if 'start_time' in action:
        # NOTE(danms): Without WSGI above us, these will be just stringified
        action['start_time'] = str(action['start_time'].replace(tzinfo=None))
    for event in action.get('events', []):
        format_event(event)
    return action


def format_event(event):
    '''Remove keys that aren't serialized.'''
    to_delete = ('id', 'created_at', 'updated_at', 'deleted_at', 'deleted',
                 'action_id')
    for key in to_delete:
        if key in event:
            del(event[key])
    if 'start_time' in event:
        # NOTE(danms): Without WSGI above us, these will be just stringified
        event['start_time'] = str(event['start_time'].replace(tzinfo=None))
    if 'finish_time' in event:
        # NOTE(danms): Without WSGI above us, these will be just stringified
        event['finish_time'] = str(event['finish_time'].replace(tzinfo=None))
    return event


class InstanceActionsPolicyTest(test.NoDBTestCase):
    def setUp(self):
        super(InstanceActionsPolicyTest, self).setUp()
        self.controller = instance_actions.InstanceActionsController()

    def test_list_actions_restricted_by_project(self):
        rules = {'compute:get': common_policy.parse_rule(''),
                 'compute_extension:instance_actions':
                     common_policy.parse_rule('project_id:%(project_id)s')}
        policy.set_rules(rules)

        def fake_instance_get_by_uuid(context, instance_id,
                                      columns_to_join=None,
                                      use_slave=False):
            return fake_instance.fake_db_instance(
                **{'name': 'fake', 'project_id': '%s_unequal' %
                       context.project_id})

        self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get_by_uuid)
        req = fakes.HTTPRequest.blank('/v2/123/servers/12/os-instance-actions')
        self.assertRaises(exception.Forbidden, self.controller.index, req,
                          str(uuid.uuid4()))

    def test_get_action_restricted_by_project(self):
        rules = {'compute:get': common_policy.parse_rule(''),
                 'compute_extension:instance_actions':
                     common_policy.parse_rule('project_id:%(project_id)s')}
        policy.set_rules(rules)

        def fake_instance_get_by_uuid(context, instance_id,
                                      columns_to_join=None,
                                      use_slave=False):
            return fake_instance.fake_db_instance(
                **{'name': 'fake', 'project_id': '%s_unequal' %
                       context.project_id})

        self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get_by_uuid)
        req = fakes.HTTPRequest.blank(
                                    '/v2/123/servers/12/os-instance-actions/1')
        self.assertRaises(exception.Forbidden, self.controller.show, req,
                          str(uuid.uuid4()), '1')


class InstanceActionsTest(test.NoDBTestCase):
    def setUp(self):
        super(InstanceActionsTest, self).setUp()
        self.controller = instance_actions.InstanceActionsController()