from datetime import timedelta
from django.contrib.auth.models import User, Group
from django.utils import timezone as tz

import pytest
from model_bakery import baker

from aircox.conf import settings
from aircox.models import signals, Diffusion, Episode


@pytest.fixture
def sched(program, sched_initials):
    return next(r for r in sched_initials if r.program == program)


@pytest.fixture
def eps_diffs(program, sched):
    eps = baker.make(Episode, program=program, _quantity=3)
    diffs = []
    for ep in eps:
        diffs += baker.make(
            Diffusion,
            start=tz.now() + timedelta(days=10),
            end=tz.now() + timedelta(days=10, hours=1),
            schedule=sched,
            episode=ep,
            _quantity=3,
        )
    return eps, diffs


@pytest.mark.django_db
def test_user_default_groups():
    user = User(username="test")
    user.save()

    default_groups = settings.DEFAULT_USER_GROUPS
    groups = Group.objects.filter(name__in=default_groups.keys())
    assert groups.exists()
    assert all(
        set(group.permissions.all().values_list("codename", flat=True)) == set(default_groups[group.name])
        for group in groups
    )
    user_groups = set(user.groups.all().values_list("name", flat=True))
    assert set(default_groups.keys()) == user_groups


@pytest.mark.django_db
def test_user_default_groups_skip_on_superuser():
    user = User(username="test", is_superuser=True)
    user.save()
    assert list(user.groups.all()) == []


@pytest.mark.django_db
def test_page_post_save(program, episodes):
    episodes = [r for r in episodes if r.program == program]
    for episode in episodes:
        episode.cover = None
    Episode.objects.bulk_update(episodes, ["cover"])
    # TODO: cover must be an fk to Image
    # program.cover = "dummy/cover.png"
    # program.save()

    # query = Episode.objects.filter(program=program) \
    #                        .values_list("cover", flat=True)
    # assert all(r == program.cover for r in query)


@pytest.mark.django_db
def test_program_post_save(program, eps_diffs):
    eps, diffs = eps_diffs
    program.active = False
    program.save()

    eps_ids = [r.id for r in eps]
    diff_ids = [r.id for r in diffs]
    assert not Episode.objects.filter(id__in=eps_ids).exists()
    assert not Diffusion.objects.filter(id__in=diff_ids).exists()


@pytest.mark.django_db
def test_schedule_pre_save(sched_initials):
    sched = sched_initials[0]
    signals.schedule_pre_save(None, sched)
    assert getattr(sched, "_initial")


@pytest.mark.django_db
def test_schedule_post_save():
    pass


@pytest.mark.django_db
def test_schedule_pre_delete(sched, eps_diffs):
    eps, diffs = eps_diffs
    signals.schedule_pre_delete(None, sched)
    assert not Episode.objects.filter(id__in=(r.id for r in eps)).exists()
    assert not Diffusion.objects.filter(id__in=(r.id for r in diffs)).exists()


@pytest.mark.django_db
def test_diffusion_post_delete(eps_diffs):
    eps = eps_diffs[0][0]
    Diffusion.objects.filter(id__in=[r.id for r in eps.diffusion_set.all()]).delete()
    assert Episode.objects.filter(id=eps.id).first() is None
