"""Proposal System Models
"""
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser, Group
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
'''
class Level(models.Model):
    """Sponsorship or Vendor Level

    The values set are defaults and can be overriden on a per Invoice basis.
    """
    name        = models.CharField(maxlength=180, unique=True,
                                   null=False, blank=False)
    amount      = models.DecimalField(default=0.0,
                                      max_digits=10, decimal_places=2)
    numreg      = models.IntegerField(
                                help_text=_("number of free registrations"))
    numvend     = models.IntegerField(
                                help_text=_("number of free vendor passes"))
    space       = models.CharField(maxlenght=180, help_text=_("describe space"))
    mindesired  = models.IntegerField(help_text=_("min desired at this level"))
    maxallowed  = models.IntegerField(help_text=_("max allowed at this level"))
    description = models.TextField(null=False, blank=False,
        help_text=_("Description for the web site describing the level. "
                    "Can use django markup, and the level object is in "
                    "the variable level."),
        validator_list=[IsValidReST("Invalid ReST Markup: ", True)])


class Organization(models.Model):
    """Organization which might become a sponsor or vendor.

    These can be potential sponsors we are trying to contact, or those
    who have signed up via an online form. Once an invoice is attached, they
    are official.
    """
    name        = models.CharField(maxlength=180, unique=True,
                                   null=False, blank=False)
    level       = models.ForeignKey(Level)
    small       = models.BooleanField(_("Small Company"))
    nonprofit   = models.BooleanField(_("Non-Profit Organization"))
    created     = models.DateTimeField(auto_now_add=True)
    PO          = models.IntegerField(blank=True)
    addr1       = models.CharField(maxlength=180, blank=True)
    addr2       = models.CharField(maxlength=180, blank=True)
    addr3       = models.CharField(maxlength=180, blank=True)
    addr4       = models.CharField(maxlength=180, blank=True)
    addr5       = models.CharField(maxlength=180, blank=True)
    sitelogo    = models.ImageField(upload_to=settings.SPONSORSHIP_UPLOAD_TO)
    vectorlogo  = models.FileField(upload_to=settings.SPONSORSHIP_UPLOAD_TO)

class Invoice(models.Model):
    """Sponsorship or Vendor Invoice

    Once an organization is officialy a sponsor or vendor, they get an invoice.
    The values set for price, space, and registrations can all be overriden
    from thier default Level values. Once the invoice is 'public' the contacts
    for the organization with login'w would be able to get the invoice online.
    """
    organization = models.ForeignKey(Organization)
    invid   = models.IntegerField(blank=True)
    date    = models.DateTimeField(auto_now_add=True)
    amount  = models.DecimalField(default=0.0, max_digits=10, decimal_places=2)
    numreg  = models.IntegerField(help_text=_("number of free registrations"))
    numvend = models.IntegerField(help_text=_("number of free vendor passes"))
    space   = models.CharField(maxlenght=180, help_text=_("describe space"))
    public  = models.BooleanField()
    message = models.TextField(blank=True)
    sent_on = models.DateTimeField(blank=true)
    paid_on = models.DateTimeField(blank=true)

class PublicFile(models.Model):
    """Other files required including imdenification, tote embroidery logo, etc.
    """
    file    = models.FileField(upload_to=settings.SPONSORSHIP_UPLOAD_TO)
    desc    = models.CharField(maxlength=180, blank=True)
    org     = models.ForeignKey(Organization)
    created = models.DateTimeField(auto_now_add=True)

class Message(models.Model):
    """Message tamplate
    """
    name    = models.CharField(maxlength=180)
    subject = models.CharField(maxlength=180)
    body    = models.TextField()

class Mailing(models.Model):
    """Mailing of a Message Template to one or more contacts
    """
    sent     = models.DateTimeField(auto_now_add=True)
    message  = models.TextField()
    contacts = models.ManyToManyField(Contact)
'''

class ContactType(models.Model):
    """List of contact types which many of which can be set on a single Contact
    Examples:
        Primary
        Billing
        CompReg
        CompVend
    """
    name = models.CharField(maxlength=180)

    class Admin: pass
    class Meta:
        ordering = ('name',)

    def __unicode__(self):
        return self.name

class Contact(models.Model):
    """Sponsorship or Vendor Contact

    Might be tied to a django login.
    The comp registrations should be listed as contacts as well.
    """
    name  = models.CharField(maxlength=180)
    email = models.EmailField(maxlength=180)
    # PhoneNumberField default to US phone validation! >.<
    phone = models.CharField(maxlength=180)
    notes = models.TextField(blank=True)
    user  = models.ForeignKey(User, blank=True, null=True)
    #organization = models.foreignKey(Organization)
    ptype = models.ForeignKey(ContactType, verbose_name=_('primary type'),
                              related_name='filter_set')
    types = models.ManyToManyField(ContactType, blank=True, null=True)

    class Admin:
        list_display  = ('name', 'email', 'phone', 'ptype')
        list_filter   = ('ptype',)
        search_fields = ('name', 'e-mail', 'phone', 'notes',)

    class Meta:
        ordering = ('name',)

    def __unicode__(self):
        return self.name

    def save(self):
        if self.user and isinstance(self.user, User):
            self.name = unicode(self.user)
            self.email = unicode(self.user.email)
            if self.user.groups.filter(name='Sponsors').count() == 0:
                sg = Group.objects.get(name='Sponsors')
                self.user.groups.add(sg)
                self.user.save()
        return super(Contact, self).save()

LEVEL_CHOICES = [ ('1:Diamond',   'Diamond'),
                  ('2:Platinum',  'Platinum'),
                  ('3:Gold',      'Gold'),
                  ('4:Silver',    'Silver'),
                  ('5:Vendor II', 'Vendor II'),
                  ('6:Vendor I',  'Vendor I')
                ]

class WebsiteLogo(models.Model):
    #organization = models.foreignKey(Organization)
    name     = models.CharField(maxlength=180)
    level    = models.CharField(maxlength=25, choices=LEVEL_CHOICES)
    index    = models.IntegerField(default=0,
                help_text=_('override sorting order within level. '
                            'sorted by level, index, time added.'))
    added    = models.DateTimeField(auto_now_add=True)
    logo     = models.ImageField(upload_to=settings.SPONSORSHIP_UPLOAD_TO)
    url      = models.URLField()
    alt      = models.CharField(maxlength=180, blank=True,
                help_text=_('hover alt text. will use name if not provided.'))
    visible  = models.BooleanField()
    contacts = models.ManyToManyField(Contact, null=True, blank=True)

    def get_absolute_url(self):
        return self.get_logo_url() # view on site

    def get_alt(self):
        if self.alt: return self.alt
        return self.name

    def safe(self):
        # RED_FLAG: Hack! set in website template!
        res =  super(WebsiteLogo, self).save()
        cache.delete('sponsor_logos')
        return res

    def __unicode__(self):
        return self.name

    class Admin:
        list_display = ('name', 'alt', 'level', 'added', 'visible')
        list_filter  = ('level', 'visible', 'added')

    class Meta:
        ordering = ('level', 'index', 'added', 'name')
