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

from socket import timeout as socket_timeout  # noqa

from django.core.urlresolvers import reverse
from django import http
from django.test.utils import override_settings

from mox import IgnoreArg  # noqa
from mox import IsA  # noqa

from openstack_dashboard import api
from openstack_dashboard.test import helpers as test


USERS_INDEX_URL = reverse('horizon:identity:users:index')
USER_CREATE_URL = reverse('horizon:identity:users:create')
USER_UPDATE_URL = reverse('horizon:identity:users:update', args=[1])
USER_DETAIL_URL = reverse('horizon:identity:users:detail', args=[1])
USER_CHANGE_PASSWORD_URL = reverse('horizon:identity:users:change_password',
                                   args=[1])


class UsersViewTests(test.BaseAdminViewTests):
    def _get_default_domain(self):
        domain = {"id": self.request.session.get('domain_context',
                                                 None),
                  "name": self.request.session.get('domain_context_name',
                                                   None)}
        return api.base.APIDictWrapper(domain)

    def _get_users(self, domain_id):
        if not domain_id:
            users = self.users.list()
        else:
            users = [user for user in self.users.list()
                     if user.domain_id == domain_id]
        return users

    @test.create_stubs({api.keystone: ('user_list',)})
    def test_index(self):
        domain = self._get_default_domain()
        domain_id = domain.id
        users = self._get_users(domain_id)
        api.keystone.user_list(IgnoreArg(),
                               domain=domain_id).AndReturn(users)

        self.mox.ReplayAll()
        res = self.client.get(USERS_INDEX_URL)
        self.assertTemplateUsed(res, 'identity/users/index.html')
        self.assertItemsEqual(res.context['table'].data, users)

        if domain_id:
            for user in res.context['table'].data:
                self.assertItemsEqual(user.domain_id, domain_id)

    def test_index_with_domain(self):
        domain = self.domains.get(id="1")
        self.setSessionValues(domain_context=domain.id,
                              domain_context_name=domain.name)
        self.test_index()

    @test.create_stubs({api.keystone: ('user_create',
                                       'get_default_domain',
                                       'tenant_list',
                                       'add_tenant_user_role',
                                       'get_default_role',
                                       'roles_for_user',
                                       'role_list')})
    def test_create(self):
        user = self.users.get(id="1")
        domain = self._get_default_domain()
        domain_id = domain.id

        role = self.roles.first()

        api.keystone.get_default_domain(IgnoreArg()) \
            .MultipleTimes().AndReturn(domain)
        api.keystone.tenant_list(IgnoreArg(),
                                 domain=domain_id,
                                 user=None) \
            .AndReturn([self.tenants.list(), False])
        api.keystone.user_create(IgnoreArg(),
                                 name=user.name,
                                 email=user.email,
                                 password=user.password,
                                 project=self.tenant.id,
                                 enabled=True,
                                 domain=domain_id).AndReturn(user)
        api.keystone.role_list(IgnoreArg()).AndReturn(self.roles.list())
        api.keystone.get_default_role(IgnoreArg()).AndReturn(role)
        api.keystone.roles_for_user(IgnoreArg(), user.id, self.tenant.id)
        api.keystone.add_tenant_user_role(IgnoreArg(), self.tenant.id,
                                          user.id, role.id)

        self.mox.ReplayAll()

        formData = {'method': 'CreateUserForm',
                    'domain_id': domain_id,
                    'name': user.name,
                    'email': user.email,
                    'password': user.password,
                    'project': self.tenant.id,
                    'role_id': self.roles.first().id,
                    'confirm_password': user.password}
        res = self.client.post(USER_CREATE_URL, formData)

        self.assertNoFormErrors(res)
        self.assertMessageCount(success=1)

    def test_create_with_domain(self):
        domain = self.domains.get(id="1")
        self.setSessionValues(domain_context=domain.id,
                              domain_context_name=domain.name)
        self.test_create()

    @test.create_stubs({api.keystone: ('user_create',
                                       'get_default_domain',
                                       'add_tenant_user_role',
                                       'tenant_list',
                                       'get_default_role',
                                       'roles_for_user',
                                       'role_list')})
    def test_create_with_empty_email(self):
        user = self.users.get(id="5")
        domain = self._get_default_domain()
        domain_id = domain.id
        role = self.roles.first()
        api.keystone.get_default_domain(IgnoreArg()) \
            .MultipleTimes().AndReturn(domain)
        api.keystone.tenant_list(IgnoreArg(),
                                 domain=domain_id,
                                 user=None) \
            .AndReturn([self.tenants.list(), False])
        api.keystone.user_create(IgnoreArg(),
                                 name=user.name,
                                 email=user.email,
                                 password=user.password,
                                 project=self.tenant.id,
                                 enabled=True,
                                 domain=domain_id).AndReturn(user)
        api.keystone.role_list(IgnoreArg()).AndReturn(self.roles.list())
        api.keystone.get_default_role(IgnoreArg()).AndReturn(role)
        api.keystone.add_tenant_user_role(IgnoreArg(), self.tenant.id,
                                          user.id, role.id)
        api.keystone.roles_for_user(IgnoreArg(), user.id, self.tenant.id)

        self.mox.ReplayAll()
        formData = {'method': 'CreateUserForm',
                    'domain_id': domain_id,
                    'name': user.name,
                    'email': "",
                    'password': user.password,
                    'project': self.tenant.id,
                    'role_id': self.roles.first().id,
                    'confirm_password': user.password}
        res = self.client.post(USER_CREATE_URL, formData)

        self.assertNoFormErrors(res)
        self.assertMessageCount(success=1)

    @test.create_stubs({api.keystone: ('get_default_domain',
                                       'tenant_list',
                                       'role_list',
                                       'get_default_role')})
    def test_create_with_password_mismatch(self):
        user = self.users.get(id="1")
        domain = self._get_default_domain()
        domain_id = domain.id

        api.keystone.get_default_domain(IgnoreArg()) \
            .MultipleTimes().AndReturn(domain)
        api.keystone.tenant_list(IgnoreArg(), domain=domain_id, user=None) \
            .AndReturn([self.tenants.list(), False])
        api.keystone.role_list(IgnoreArg()).AndReturn(self.roles.list())
        api.keystone.get_default_role(IgnoreArg()) \
                    .AndReturn(self.roles.first())

        self.mox.ReplayAll()

        formData = {'method': 'CreateUserForm',
                    'domain_id': domain_id,
                    'name': user.name,
                    'email': user.email,
                    'password': user.password,
                    'project': self.tenant.id,
                    'role_id': self.roles.first().id,
                    'confirm_password': "doesntmatch"}

        res = self.client.post(USER_CREATE_URL, formData)

        self.assertFormError(res, "form", None, ['Passwords do not match.'])

    @test.create_stubs({api.keystone: ('get_default_domain',
                                       'tenant_list',
                                       'role_list',
                                       'get_default_role')})
    def test_create_validation_for_password_too_short(self):
        user = self.users.get(id="1")
        domain = self._get_default_domain()
        domain_id = domain.id

        api.keystone.get_default_domain(IgnoreArg()) \
            .MultipleTimes().AndReturn(domain)
        api.keystone.tenant_list(IgnoreArg(), domain=domain_id, user=None) \
            .AndReturn([self.tenants.list(), False])
        api.keystone.role_list(IgnoreArg()).AndReturn(self.roles.list())
        api.keystone.get_default_role(IgnoreArg()) \
                    .AndReturn(self.roles.first())

        self.mox.ReplayAll()

        # check password min-len verification
        formData = {'method': 'CreateUserForm',
                    'domain_id': domain_id,
                    'name': user.name,
                    'email': user.email,
                    'password': 'four',
                    'project': self.tenant.id,
                    'role_id': self.roles.first().id,
                    'confirm_password': 'four'}

        res = self.client.post(USER_CREATE_URL, formData)

        self.assertFormError(
            res, "form", 'password',
            ['Password must be between 8 and 18 characters.'])

    @test.create_stubs({api.keystone: ('get_default_domain',
                                       'tenant_list',
                                       'role_list',
                                       'get_default_role')})
    def test_create_validation_for_password_too_long(self):
        user = self.users.get(id="1")
        domain = self._get_default_domain()
        domain_id = domain.id

        api.keystone.get_default_domain(IgnoreArg()) \