# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
#    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 tempfile

from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile  # noqa
from django.core.urlresolvers import reverse
from django.forms.widgets import HiddenInput  # noqa
from django import http
from django.test.utils import override_settings

from mox import IsA  # noqa

from horizon import tables as horizon_tables
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test

from openstack_dashboard.dashboards.project.images.images import forms
from openstack_dashboard.dashboards.project.images.images import tables


IMAGES_INDEX_URL = reverse('horizon:project:images:index')


class CreateImageFormTests(test.TestCase):
    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_no_location_or_file(self):
        filters = {'disk_format': 'aki'}
        api.glance.image_list_detailed(
            IsA({}), filters=filters).AndReturn(
            [self.images.list(), False, False])
        filters = {'disk_format': 'ari'}
        api.glance.image_list_detailed(
            IsA({}), filters=filters).AndReturn(
            [self.images.list(), False, False])
        self.mox.ReplayAll()
        post = {
            'name': u'Ubuntu 11.10',
            'source_type': u'file',
            'description': u'Login with admin/admin',
            'disk_format': u'qcow2',
            'architecture': u'x86-64',
            'minimum_disk': 15,
            'minimum_ram': 512,
            'is_public': 1}
        files = {}
        form = forms.CreateImageForm(post, files)
        self.assertEqual(form.is_valid(), False)

    @override_settings(HORIZON_IMAGES_ALLOW_UPLOAD=False)
    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_image_upload_disabled(self):
        filters = {'disk_format': 'aki'}
        api.glance.image_list_detailed(
            IsA({}), filters=filters).AndReturn(
            [self.images.list(), False, False])
        filters = {'disk_format': 'ari'}
        api.glance.image_list_detailed(
            IsA({}), filters=filters).AndReturn(
            [self.images.list(), False, False])
        self.mox.ReplayAll()
        form = forms.CreateImageForm({})
        self.assertEqual(
            isinstance(form.fields['image_file'].widget, HiddenInput), True)
        source_type_dict = dict(form.fields['source_type'].choices)
        self.assertNotIn('file', source_type_dict)

    def test_create_image_metadata_docker(self):
        form_data = {
            'name': u'Docker image',
            'description': u'Docker image test',
            'source_type': u'url',
            'image_url': u'/',
            'disk_format': u'docker',
            'architecture': u'x86-64',
            'minimum_disk': 15,
            'minimum_ram': 512,
            'is_public': False,
            'protected': False,
            'is_copying': False
        }
        meta = forms.create_image_metadata(form_data)
        self.assertEqual(meta['disk_format'], 'raw')
        self.assertEqual(meta['container_format'], 'docker')
        self.assertIn('properties', meta)
        self.assertNotIn('description', meta)
        self.assertNotIn('architecture', meta)
        self.assertEqual(meta['properties']['description'],
                         form_data['description'])
        self.assertEqual(meta['properties']['architecture'],
                         form_data['architecture'])


class UpdateImageFormTests(test.TestCase):
    def test_is_format_field_editable(self):
        form = forms.UpdateImageForm({})
        disk_format = form.fields['disk_format']
        self.assertFalse(disk_format.widget.attrs.get('readonly', False))

    @test.create_stubs({api.glance: ('image_get',)})
    def test_image_update(self):
        image = self.images.first()
        api.glance.image_get(IsA(http.HttpRequest), str(image.id)) \
           .AndReturn(image)
        self.mox.ReplayAll()

        url = reverse('horizon:project:images:images:update',
                      args=[image.id])
        res = self.client.get(url)
        self.assertNoFormErrors(res)
        self.assertEqual(res.context['image'].disk_format,
                         image.disk_format)

    @test.create_stubs({api.glance: ('image_update', 'image_get')})
    def test_image_update_post(self):
        image = self.images.first()
        data = {
            'name': u'Ubuntu 11.10',
            'image_id': str(image.id),
            'description': u'Login with admin/admin',
            'source_type': u'url',
            'image_url': u'http://cloud-images.ubuntu.com/releases/'
                         u'oneiric/release/ubuntu-11.10-server-cloudimg'
                         u'-amd64-disk1.img',
            'disk_format': u'qcow2',
            'architecture': u'x86-64',
            'minimum_disk': 15,
            'minimum_ram': 512,
            'is_public': False,
            'protected': False,
            'method': 'UpdateImageForm'}
        api.glance.image_get(IsA(http.HttpRequest), str(image.id)) \
           .AndReturn(image)
        api.glance.image_update(IsA(http.HttpRequest),
                                image.id,
                                is_public=data['is_public'],
                                protected=data['protected'],
                                disk_format=data['disk_format'],
                                container_format="bare",
                                name=data['name'],
                                min_ram=data['minimum_ram'],
                                min_disk=data['minimum_disk'],
                                properties={'description': data['description'],
                                            'architecture':
                                            data['architecture']},
                                purge_props=False).AndReturn(image)
        self.mox.ReplayAll()
        url = reverse('horizon:project:images:images:update',
                      args=[image.id])
        res = self.client.post(url, data)
        self.assertNoFormErrors(res)
        self.assertEqual(res.status_code, 302)


class ImageViewTests(test.TestCase):
    @test.create_stubs({api.glance: ('image_list_detailed',)})
    def test_image_create_get(self):
        filters = {'disk_format': 'aki'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        filters = {'disk_format': 'ari'}
        api.glance.image_list_detailed(
            IsA(http.HttpRequest), filters=filters).AndReturn(
            [self.images.list(), False, False])
        self.mox.ReplayAll()

        url = reverse('horizon:project:images:images:create')
        res = self.client.get(url)
        self.assertTemplateUsed(res,
                                'project/images/images/create.html')

    @test.create_stubs({api.glance: ('image_create',)})
    def test_image_create_post_copy_from(self):
        data = {
            'source_type': u'url',
            'image_url': u'http://cloud-images.ubuntu.com/releases/'
                         u'oneiric/release/ubuntu-11.10-server-cloudimg'
                         u'-amd64-disk1.img',
            'is_copying': True}

        api_data = {'copy_from': data['image_url']}
        self._test_image_create(data, api_data)

    @test.create_stubs({api.glance: ('image_create',)})
    def test_image_create_post_location(self):
        data = {
            'source_type': u'url',
            'image_url': u'http://cloud-images.ubuntu.com/releases/'
                         u'oneiric/release/ubuntu-11.10-server-cloudimg'
                         u'-amd64-disk1.img',
            'is_copying': False}

        api_data = {'location': data['image_url']}
        self._test_image_create(data, api_data)

    @test.create_stubs({api.glance: ('image_create',)})
    def test_image_create_post_upload(self):
        temp_file = tempfile.TemporaryFile()
        temp_file.write('123')
        temp_file.flush()
        temp_file.seek(0)

        data = {'source_type': u'file',
                'image_file': temp_file}

        api_data = {'data': IsA(InMemoryUploadedFile)}
        self._test_image_create(data, api_data)

    @test.create_stubs({api.glance: ('image_create',)})
    def test_image_create_post_with_kernel_ramdisk(self):