# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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.

from heatclient.v1 import stacks
import mock

from murano.dsl import class_loader
from murano.dsl import murano_class
from murano.dsl import object_store
from murano.engine import client_manager
from murano.engine.system import heat_stack
from murano.tests.unit import base


MOD_NAME = 'murano.engine.system.heat_stack'


class TestHeatStack(base.MuranoTestCase):
    def setUp(self):
        super(TestHeatStack, self).setUp()
        self.mock_murano_class = mock.Mock(spec=murano_class.MuranoClass)
        self.mock_murano_class.name = 'io.murano.system.HeatStack'
        self.mock_murano_class.parents = []
        self.heat_client_mock = mock.MagicMock()
        self.heat_client_mock.stacks = mock.MagicMock(spec=stacks.StackManager)
        self.mock_object_store = mock.Mock(spec=object_store.ObjectStore)
        self.mock_object_store.class_loader = mock.Mock(
            spec=class_loader.MuranoClassLoader)
        self.client_manager_mock = mock.Mock(
            spec=client_manager.ClientManager)

        self.client_manager_mock.get_heat_client.return_value = \
            self.heat_client_mock

    def test_push_adds_version(self):
        """Assert that if heat_template_version is omitted, it's added."""
        # Note that the 'with x as y, a as b:' syntax was introduced in
        # python 2.7, and contextlib.nested was deprecated in py2.7
        with mock.patch(MOD_NAME + '.HeatStack._get_status') as status_get:
            with mock.patch(MOD_NAME + '.HeatStack._wait_state') as wait_st:

                status_get.return_value = 'NOT_FOUND'
                wait_st.return_value = {}

                hs = heat_stack.HeatStack(self.mock_murano_class,
                                          None, self.mock_object_store, None)
                hs._name = 'test-stack'
                hs._description = 'Generated by TestHeatStack'
                hs._template = {'resources': {'test': 1}}
                hs._parameters = {}
                hs._applied = False
                hs._clients = self.client_manager_mock
                hs.push(None)

                expected_template = {
                    'heat_template_version': '2013-05-23',
                    'description': 'Generated by TestHeatStack',
                    'resources': {'test': 1}
                }
                self.heat_client_mock.stacks.create.assert_called_with(
                    stack_name='test-stack',
                    disable_rollback=True,
                    parameters={},
                    template=expected_template
                )
                self.assertTrue(hs._applied)

    def test_description_is_optional(self):
        """Assert that if heat_template_version is omitted, it's added."""
        # Note that the 'with x as y, a as b:' syntax was introduced in
        # python 2.7, and contextlib.nested was deprecated in py2.7
        with mock.patch(MOD_NAME + '.HeatStack._get_status') as status_get:
            with mock.patch(MOD_NAME + '.HeatStack._wait_state') as wait_st:

                status_get.return_value = 'NOT_FOUND'
                wait_st.return_value = {}

                hs = heat_stack.HeatStack(self.mock_murano_class,
                                          None, self.mock_object_store, None)
                hs._clients = self.client_manager_mock
                hs._name = 'test-stack'
                hs._description = None
                hs._template = {'resources': {'test': 1}}
                hs._parameters = {}
                hs._applied = False
                hs.push(None)

                expected_template = {
                    'heat_template_version': '2013-05-23',
                    'resources': {'test': 1}
                }
                self.heat_client_mock.stacks.create.assert_called_with(
                    stack_name='test-stack',
                    disable_rollback=True,
                    parameters={},
                    template=expected_template
                )
                self.assertTrue(hs._applied)

    def test_update_wrong_template_version(self):
        """Template version other than expected should cause error."""

        hs = heat_stack.HeatStack(self.mock_murano_class,
                                  None, self.mock_object_store, None)
        hs._name = 'test-stack'
        hs._description = 'Generated by TestHeatStack'
        hs._template = {'resources': {'test': 1}}
        hs.type.properties = {}

        invalid_template = {
            'heat_template_version': 'something else'
        }

        with mock.patch(MOD_NAME + '.HeatStack.current') as current:
            current.return_value = {}

            e = self.assertRaises(heat_stack.HeatStackError,
                                  hs.updateTemplate,
                                  None,
                                  invalid_template)
            err_msg = "Currently only heat_template_version 2013-05-23 "\
                      "is supported."
            self.assertEqual(err_msg, str(e))

            # Check it's ok without a version
            hs.updateTemplate(None, {})
            expected = {'resources': {'test': 1}}
            self.assertEqual(expected, hs._template)

            # .. or with a good version
            hs.updateTemplate(None, {'heat_template_version': '2013-05-23'})
            expected['heat_template_version'] = '2013-05-23'
            self.assertEqual(expected, hs._template)
