from datetime import timedelta

from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone

from bda.models import (
    Attribution,
    CategorieSpectacle,
    Participant,
    Salle,
    Spectacle,
    SpectacleRevente,
    Tirage,
)


class TestModels(TestCase):
    def setUp(self):
        self.tirage = Tirage.objects.create(
            title="Tirage test",
            appear_catalogue=True,
            ouverture=timezone.now(),
            fermeture=timezone.now(),
        )
        self.category = CategorieSpectacle.objects.create(name="Category")
        self.location = Salle.objects.create(name="here")
        self.spectacle_soon = Spectacle.objects.create(
            title="foo",
            date=timezone.now() + timedelta(days=1),
            location=self.location,
            price=0,
            slots=42,
            tirage=self.tirage,
            listing=False,
            category=self.category,
        )
        self.spectacle_later = Spectacle.objects.create(
            title="bar",
            date=timezone.now() + timedelta(days=30),
            location=self.location,
            price=0,
            slots=42,
            tirage=self.tirage,
            listing=False,
            category=self.category,
        )

        user_buyer = User.objects.create_user(
            username="bda_buyer", password="testbuyer"
        )
        user_seller = User.objects.create_user(
            username="bda_seller", password="testseller"
        )
        self.buyer = Participant.objects.create(user=user_buyer, tirage=self.tirage)
        self.seller = Participant.objects.create(user=user_seller, tirage=self.tirage)

        self.attr_soon = Attribution.objects.create(
            participant=self.seller, spectacle=self.spectacle_soon
        )
        self.attr_later = Attribution.objects.create(
            participant=self.seller, spectacle=self.spectacle_later
        )
        self.revente_soon = SpectacleRevente.objects.create(
            seller=self.seller, attribution=self.attr_soon
        )
        self.revente_later = SpectacleRevente.objects.create(
            seller=self.seller, attribution=self.attr_later
        )

    def test_urgent(self):
        self.assertTrue(self.revente_soon.is_urgent)
        self.assertFalse(self.revente_later.is_urgent)

    def test_tirage(self):
        self.revente_soon.confirmed_entry.add(self.buyer)

        self.assertEqual(self.revente_soon.tirage(send_mails=False), self.buyer)
        self.assertIsNone(self.revente_later.tirage(send_mails=False))
