import json

from django.contrib.auth.models import Group

from ichec_django_core.models import Member
from ichec_django_core.client.resources import create_groups
from ichec_django_core.test import (
    AuthAPITestCase,
    setup_default_users_and_groups,
    add_group_permissions,
)


class TestGroupView(AuthAPITestCase):
    def setUp(self):
        self.url = "/api/groups/"
        self.template = create_groups(1)[0]
        setup_default_users_and_groups()

        add_group_permissions(
            "admins",
            Group,
            ["view_group", "change_group", "add_group"],
        )

        add_group_permissions(
            "admins",
            Member,
            ["view_member"],
        )

    def test_list_access(self):

        scenarios = (
            ["", 0, 401, "Public can't list groups"],
            ["regular_user", 1, 200, "Registered can list own groups"],
            ["member", 2, 200, "Member can list own groups"],
            ["admin_user", 3, 200, "Admin can list all groups"],
        )

        for user, count, status, msg in scenarios:
            if user:
                response = self.assert_status(self.auth_list(user), status, msg)
            else:
                response = self.assert_status(self.public_list(), status, msg)

            if status < 400:
                self.assertEqual(response.body.count, count, msg)

    def test_detail_access(self):

        regular_id = Group.objects.get(name="regular_users").id

        scenarios = (
            ["", regular_id, 401, "Public can't view group detail"],
            ["regular_user", regular_id, 403, "Regular user can't view group detail"],
            ["member", regular_id, 403, "Member can't view group detail"],
            ["admin_user", regular_id, 200, "Admin can view group detail"],
        )

        for user, item, status, msg in scenarios:
            if user:
                self.assert_status(self.auth_detail(user, item), status, msg)
            else:
                self.assert_status(self.detail(item), status, msg)

    def test_create_not_authenticated(self):
        data = {"name": "My Group"}
        self.assert_401(self.create(self.template))

    def test_create_authenticated_no_permission(self):
        data = {"name": "My Group"}
        self.assert_403(self.auth_create("regular_user", self.template))

    def test_filter_user(self):
        admin_id = Member.objects.get(username="admin_user").id
        response = self.assert_status(
            self.auth_list("admin_user", {"user": admin_id}), 200
        )
        self.assertEqual(response.body.count, 3)

        member_id = Group.objects.get(name="regular_users").id
        response = self.assert_status(
            self.auth_raw_get("admin_user", "/api/members/", {"groups__id": member_id}),
            200,
        )
        self.assertEqual(response.body["count"], 5)
