# (c) cavaliba.com - test_user.py

import yaml

from django.test import override_settings
from django.test import TestCase
from django.test import TransactionTestCase
from django.urls import reverse
from django.core.cache import cache as cache_django
from django.core.management import call_command

from tests import helper

from app_user.user import user_get_by_login

from app_user.group import group_get_by_name
from app_user.group import group_get_users

from app_user.group import group_autogroup_update

import app_home.cache as cache
from app_data.loader import load_broker


#   autogroup
class Autogroup(TestCase):

    def setUp(self):
        cache.clear()

        with open("./tests/data2/autogroup.yaml") as stream:
            try:
                datalist = yaml.safe_load(stream)
            except yaml.YAMLError as exc:
                print(exc)

        aaa = {
            'perms': [
                'p_group_create',
                'p_user_create',
                'p_schema_write',
                'p_data_admin']}
        _ = load_broker(datalist=datalist, aaa=aaa)

    def test_no_grammar(self):

        user = user_get_by_login('user99')
        self.assertIsNotNone(user)

        group1 = group_get_by_name('group1')
        self.assertIsNotNone(group1)

        users = group_get_users(group1)
        self.assertEqual(len(users), 1)
        self.assertIn(user, group1.users.all())

    def test_g1_grammar(self):

        group = group_get_by_name('group2')
        self.assertEqual(group.autogroup, 'site:*:manager')

        users = group_get_users(group)
        self.assertEqual(len(users), 4)

        user1 = user_get_by_login('user1')
        user3 = user_get_by_login('user3')
        user5 = user_get_by_login('user5')
        user99 = user_get_by_login('user99')

        self.assertIn(user99, users)
        self.assertIn(user1, users)
        self.assertIn(user3, users)
        self.assertIn(user5, users)

    def test_g2_grammar(self):

        group = group_get_by_name('group3')
        self.assertEqual(group.autogroup, 'site:site1:*')

        users = group_get_users(group)
        self.assertEqual(len(users), 3)

        user1 = user_get_by_login('user1')
        user2 = user_get_by_login('user2')
        user99 = user_get_by_login('user99')

        self.assertIn(user99, users)
        self.assertIn(user1, users)
        self.assertIn(user2, users)

    def test_autogroup_update(self):

        count = group_autogroup_update()
        self.assertEqual(count, 2)

        group = group_get_by_name('group3')
        count = group_autogroup_update([group])
        self.assertEqual(count, 1)

        count = group_autogroup_update([])
        self.assertEqual(count, 2)
