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

import mock
from oslo_config import cfg
from oslo_utils import timeutils
from six.moves.urllib import parse as urlparse
from wsme import types as wtypes

from magnum.api.controllers.v1 import pod as api_pod
from magnum.common import utils
from magnum.conductor import api as rpcapi
from magnum import objects
from magnum.tests import base
from magnum.tests.unit.api import base as api_base
from magnum.tests.unit.api import utils as apiutils
from magnum.tests.unit.objects import utils as obj_utils


class TestPodObject(base.TestCase):

    def test_pod_init(self):
        pod_dict = apiutils.pod_post_data(bay_uuid=None)
        del pod_dict['desc']
        pod = api_pod.Pod(**pod_dict)
        self.assertEqual(wtypes.Unset, pod.desc)


class TestListPod(api_base.FunctionalTest):

    def setUp(self):
        super(TestListPod, self).setUp()
        obj_utils.create_test_bay(self.context)

    def test_empty(self):
        response = self.get_json('/pods')
        self.assertEqual([], response['pods'])

    def _assert_pod_fields(self, pod):
        pod_fields = ['name', 'bay_uuid', 'desc', 'images', 'labels',
                      'status', 'host']
        for field in pod_fields:
            self.assertIn(field, pod)

    def test_one(self):
        pod = obj_utils.create_test_pod(self.context)
        response = self.get_json('/pods')
        self.assertEqual(pod.uuid, response['pods'][0]["uuid"])
        self._assert_pod_fields(response['pods'][0])

    def test_get_one(self):
        pod = obj_utils.create_test_pod(self.context)
        response = self.get_json('/pods/%s' % pod['uuid'])
        self.assertEqual(pod.uuid, response['uuid'])
        self._assert_pod_fields(response)

    def test_get_one_by_name(self):
        pod = obj_utils.create_test_pod(self.context)
        response = self.get_json('/pods/%s' % pod['name'])
        self.assertEqual(pod.uuid, response['uuid'])
        self._assert_pod_fields(response)

    def test_get_one_by_name_not_found(self):
        response = self.get_json('/pods/not_found', expect_errors=True)
        self.assertEqual(response.status_int, 404)
        self.assertEqual('application/json', response.content_type)
        self.assertTrue(response.json['error_message'])

    def test_get_one_by_name_multiple_pod(self):
        obj_utils.create_test_pod(self.context, name='test_pod',
                                  uuid=utils.generate_uuid())
        obj_utils.create_test_pod(self.context, name='test_pod',
                                  uuid=utils.generate_uuid())
        response = self.get_json('/pods/test_pod', expect_errors=True)
        self.assertEqual(response.status_int, 409)
        self.assertEqual('application/json', response.content_type)
        self.assertTrue(response.json['error_message'])

    def test_detail(self):
        pod = obj_utils.create_test_pod(self.context)
        response = self.get_json('/pods/detail')
        self.assertEqual(pod.uuid, response['pods'][0]["uuid"])
        self._assert_pod_fields(response['pods'][0])

    def test_detail_against_single(self):
        pod = obj_utils.create_test_pod(self.context)
        response = self.get_json('/pods/%s/detail' % pod['uuid'],
                                 expect_errors=True)
        self.assertEqual(404, response.status_int)

    def test_many(self):
        pod_list = []
        for id_ in range(5):
            pod = obj_utils.create_test_pod(self.context, id=id_,
                                            uuid=utils.generate_uuid())
            pod_list.append(pod.uuid)
        response = self.get_json('/pods')
        self.assertEqual(len(pod_list), len(response['pods']))
        uuids = [p['uuid'] for p in response['pods']]
        self.assertEqual(sorted(pod_list), sorted(uuids))

    def test_links(self):
        uuid = utils.generate_uuid()
        obj_utils.create_test_pod(self.context, id=1, uuid=uuid)
        response = self.get_json('/pods/%s' % uuid)
        self.assertIn('links', response.keys())
        self.assertEqual(2, len(response['links']))
        self.assertIn(uuid, response['links'][0]['href'])
        for l in response['links']:
            bookmark = l['rel'] == 'bookmark'
            self.assertTrue(self.validate_link(l['href'], bookmark=bookmark))

    def test_collection_links(self):
        for id_ in range(5):