from django.db import models
from django.utils import timezone
from django.utils.text import slugify


class MotionEvent(models.Model):
    name = models.CharField(max_length=255, help_text='Short title for the motion')
    slug = models.SlugField(max_length=255, unique=True, blank=True)
    description = models.TextField(blank=True, help_text='Full text of the motion being seconded')
    is_active = models.BooleanField(default=True)
    is_archived = models.BooleanField(default=False)
    archived_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name = 'Motion Event'
        verbose_name_plural = 'Motion Events'

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    def archive(self):
        self.is_archived = True
        self.is_active = False
        self.archived_at = timezone.now()
        self.save(update_fields=['is_archived', 'is_active', 'archived_at'])

    @property
    def yes_count(self):
        return self.votes.filter(vote='YES').count()

    @property
    def no_count(self):
        return self.votes.filter(vote='NO').count()

    @property
    def total_votes(self):
        return self.votes.count()


class MotionVote(models.Model):
    VOTE_CHOICES = [('YES', 'Yes — I second the motion'), ('NO', 'No — I oppose the motion')]

    event = models.ForeignKey(MotionEvent, on_delete=models.CASCADE, related_name='votes')
    registration_code = models.CharField(max_length=100)
    full_name = models.CharField(max_length=255, blank=True)
    vote = models.CharField(max_length=3, choices=VOTE_CHOICES)
    voted_at = models.DateTimeField(auto_now_add=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)

    class Meta:
        ordering = ['-voted_at']
        unique_together = [('event', 'registration_code')]
        verbose_name = 'Motion Vote'
        verbose_name_plural = 'Motion Votes'

    def __str__(self):
        return f'{self.full_name or self.registration_code} voted {self.vote} — {self.event.name}'
