from django.test import TestCase
from django.contrib.auth import get_user_model
from django.forms import ModelChoiceField

from accrete import models
from accrete import forms
from accrete.tenant import set_tenant

User = get_user_model()


class TestForm(forms.TenantForm):

    members = ModelChoiceField(
        queryset=models.Member.objects.all()
    )


class FormTestCase(TestCase):

    def setUp(self):
        self.tenant = models.Tenant(name='Test Tenant')
        self.tenant.save()
        self.user = User(email='test@user.test', username='Test User')
        self.user.save()

    def test_modelform_set_tenant(self):
        set_tenant(self.tenant)
        f = forms.TenantForm()
        self.assertEqual(self.tenant, f.tenant)
        set_tenant(None)

    def test_modelform_tenant_queryset(self):
        set_tenant(self.tenant)
        f = TestForm()
        self.assertQuerySetEqual(
            f.fields['members'].queryset,
            models.Member.objects.filter(tenant=self.tenant)
        )
        set_tenant(None)

    def test_modelform_clean_staff(self):
        self.user.is_staff = True
        self.user.save()
        tenant = models.Tenant(name='Test 1')
        tenant.save()
        tenant_2 = models.Tenant(name='Test 2')
        tenant_2.save()
        member = models.Member(user=self.user, tenant=tenant)
        member.save()
        member_2 = models.Member(user=self.user, tenant=tenant_2)
        member_2.save()
        set_tenant(tenant)
        f = TestForm()
        self.assertQuerySetEqual(f.fields['members'].queryset, models.Member.objects.filter(pk=member.pk))
        set_tenant(None)

    def test_modelform_no_tenant(self):
        set_tenant(None)
        f = TestForm()
        self.assertQuerySetEqual(
            f.fields['members'].queryset,
            models.Member.objects.none()
        )

    def test_modelform_with_member(self):
        member = models.Member(
            tenant=self.tenant,
            user=self.user
        )
        member.save()
        set_tenant(self.tenant)
        f = forms.TenantForm({})
        self.assertTrue(f.is_valid())
        set_tenant(None)
