import json
from django.test import TestCase
from django.contrib.auth import get_user_model
from accrete.contrib import ui
from accrete.models import Tenant, Member

User = get_user_model()


class FilterTestCase(TestCase):

    def setUp(self):
        super().setUp()
        self.tenant1 = Tenant(name='tenant 1')
        self.tenant1.save()
        self.tenant2 = Tenant(name='tenant2')
        self.tenant2.save()

        self.pezi = User(email='pezi@test.com', username='pezi')
        self.pezi.save()
        self.dagobert = User(email='dagobert@test.com', username='dagobert')
        self.dagobert.save()

        self.member_pezi = Member(tenant=self.tenant1, user=self.pezi)
        self.member_pezi.save()
        self.member_dagobert = Member(tenant=self.tenant1, user=self.dagobert)
        self.member_dagobert.save()
        self.member_dagobert2 = Member(tenant=self.tenant2, user=self.dagobert)
        self.member_dagobert2.save()

    def test_get_page(self):
        f = ui.Filter(
            model=Member,
            query_dict={'q': json.dumps({'tenant__id__exact': self.tenant1.pk})},
        )
        self.assertQuerySetEqual(
            f.get_page().object_list,
            Member.objects.filter(
                pk__in=[self.member_pezi.pk, self.member_dagobert.pk]
            )
        )
        f = ui.Filter(
            model=Member,
            query_dict={'q': json.dumps({'tenant__id__exact': self.tenant2.pk})},
        )
        self.assertQuerySetEqual(
            f.get_page().object_list,
            Member.objects.filter(pk__in=[self.member_dagobert2.pk])
        )
