# Imports from Django
from django.db import models
from django.template.defaultfilters import slugify

class Survey(models.Model):
    title = models.CharField(max_length=30, help_text="The name of this survey.")
    description = models.TextField(blank=True, null=True, help_text="An optional description of this survey.")
    questions = models.ManyToManyField('Poll')
    slug = models.SlugField(help_text="Used for URLs. Autogenerated from title.")

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return '/surveys/%s/' % self.slug

class Poll(models.Model):
    """Provide the basis of the poll framework. Should be pretty simple."""
    pub_date = models.DateField('date published')
    question = models.CharField(max_length=255)
    slug = models.SlugField(db_index=True, unique_for_date='pub_date', help_text="Used for URLs. Autogenerated from question.")
    last_updated = models.DateTimeField(blank=True, null=True, auto_now=True, help_text="When this poll was last updated. The site will automatically update this field whenever the poll is saved.")
    voting_ends = models.DateTimeField('date to close voting', null=True)

    mediatype = 'poll'
    
    def __unicode__(self):
        return self.question
    def get_absolute_url(self):
        return '/polls/%s/' % self.id
    
    class Meta:
        get_latest_by = 'pub_date'
        ordering = ['-pub_date']

class Choice(models.Model):
    """Provide support for an arbitrary number of choices.
    
    Meant to be edited inline with Poll.
    
    """
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=255)
    
    def __unicode__(self):
        return u'%s: %s' % (self.poll, self.choice)
    
    class Meta:
        ordering = ['poll']
        unique_together = (('poll', 'choice'),)

class Vote(models.Model):
    """Allow the site to store individual votes.
    
    Not intended to be edited directly.
    
    """
    poll = models.ForeignKey(Poll)
    vote = models.ForeignKey(Choice)
    unique_id = models.CharField(max_length=255, db_index=True)
    
    def __unicode__(self):
        s = u'%s-%s-%s' % (self.poll, self.vote, self.unique_id)
        return slugify(s)
    
    class Meta:
        ordering = ['poll', 'vote', 'unique_id']
        unique_together = (('poll', 'unique_id'),)
