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

from heat.engine.clients.os.keystone import fake_keystoneclient as fake_ks
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine.resources.openstack.keystone import endpoint
from heat.engine import stack
from heat.engine import template
from heat.tests import common
from heat.tests import utils

keystone_endpoint_template = {
    'heat_template_version': '2015-04-30',
    'resources': {
        'test_endpoint': {
            'type': 'OS::Keystone::Endpoint',
            'properties': {
                'service': 'heat',
                'region': 'RegionOne',
                'interface': 'public',
                'url': 'http://127.0.0.1:8004/v1/tenant-id',
                'name': 'endpoint_foo',
                'enabled': False
            }
        }
    }
}


class KeystoneEndpointTest(common.HeatTestCase):
    def setUp(self):
        super(KeystoneEndpointTest, self).setUp()

        self.ctx = utils.dummy_context()

        # Mock client
        self.keystoneclient = mock.Mock()
        self.patchobject(resource.Resource, 'client',
                         return_value=fake_ks.FakeKeystoneClient(
                             client=self.keystoneclient))
        self.endpoints = self.keystoneclient.endpoints

        # Mock client plugin
        self.keystone_client_plugin = mock.MagicMock()

    def _get_mock_endpoint(self):
        value = mock.MagicMock()
        value.id = '477e8273-60a7-4c41-b683-fdb0bc7cd152'

        return value

    def _setup_endpoint_resource(self, stack_name, use_default=False):
        tmpl_data = copy.deepcopy(keystone_endpoint_template)
        if use_default:
            props = tmpl_data['resources']['test_endpoint']['properties']
            del props['name']
            del props['enabled']

        test_stack = stack.Stack(
            self.ctx, stack_name,
            template.Template(tmpl_data)
        )

        r_endpoint = test_stack['test_endpoint']
        r_endpoint.client = mock.MagicMock()
        r_endpoint.client.return_value = self.keystoneclient
        r_endpoint.client_plugin = mock.MagicMock()
        r_endpoint.client_plugin.return_value = self.keystone_client_plugin

        return r_endpoint

    def test_endpoint_handle_create(self):
        rsrc = self._setup_endpoint_resource('test_endpoint_create')
        mock_endpoint = self._get_mock_endpoint()
        self.endpoints.create.return_value = mock_endpoint

        # validate the properties
        self.assertEqual(
            'heat', rsrc.properties.get(endpoint.KeystoneEndpoint.SERVICE))
        self.assertEqual(
            'public',
            rsrc.properties.get(endpoint.KeystoneEndpoint.INTERFACE))
        self.assertEqual(
            'RegionOne',
            rsrc.properties.get(endpoint.KeystoneEndpoint.REGION))
        self.assertEqual(
            'http://127.0.0.1:8004/v1/tenant-id',
            rsrc.properties.get(endpoint.KeystoneEndpoint.SERVICE_URL))
        self.assertEqual(
            'endpoint_foo',
            rsrc.properties.get(endpoint.KeystoneEndpoint.NAME))
        self.assertFalse(rsrc.properties.get(
            endpoint.KeystoneEndpoint.ENABLED))

        rsrc.handle_create()

        # validate endpoint creation
        self.endpoints.create.assert_called_once_with(
            service='heat',
            url='http://127.0.0.1:8004/v1/tenant-id',
            interface='public',
            region='RegionOne',
            name='endpoint_foo',
            enabled=False)

        # validate physical resource id
        self.assertEqual(mock_endpoint.id, rsrc.resource_id)

    def test_endpoint_handle_create_default(self):
        rsrc = self._setup_endpoint_resource('test_create_with_defaults',
                                             use_default=True)
        mock_endpoint = self._get_mock_endpoint()
        self.endpoints.create.return_value = mock_endpoint

        rsrc.physical_resource_name = mock.MagicMock()
        rsrc.physical_resource_name.return_value = 'stack_endpoint_foo'

        # validate the properties
        self.assertIsNone(
            rsrc.properties.get(endpoint.KeystoneEndpoint.NAME))
        self.assertTrue(rsrc.properties.get(
            endpoint.KeystoneEndpoint.ENABLED))

        rsrc.handle_create()

        # validate endpoints creation with physical resource name
        # and with enabled(default is True)
        self.endpoints.create.assert_called_once_with(
            service='heat',
            url='http://127.0.0.1:8004/v1/tenant-id',
            interface='public',
            region='RegionOne',
            name='stack_endpoint_foo',
            enabled=True)

    def test_endpoint_handle_update(self):
        rsrc = self._setup_endpoint_resource('test_endpoint_update')
        rsrc.resource_id = '477e8273-60a7-4c41-b683-fdb0bc7cd151'

        prop_diff = {endpoint.KeystoneEndpoint.REGION: 'RegionTwo',
                     endpoint.KeystoneEndpoint.INTERFACE: 'internal',
                     endpoint.KeystoneEndpoint.SERVICE: 'updated_id',
                     endpoint.KeystoneEndpoint.SERVICE_URL:
                         'http://127.0.0.1:8004/v2/tenant-id',
                     endpoint.KeystoneEndpoint.NAME: