# portfolio/models.py

from django.db import models
from django.db.models import permalink
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

from markdown import markdown
from tagging.fields import TagField
import tagging

from level0.fields import PositionField
from level0.media.models import *
from level0.contacts.models import Entity, Person
#from level0.organize.models import Category, CategoryItem

from level0.portfolio.managers import *

class Discipline(models.Model):
    """
    
        The disciplines involved in a project.
    
    """
    name = models.CharField(max_length=250)
    slug = models.SlugField(unique=True, help_text="Suggested value automatically generated from title. Must be unique.")
    
    def __unicode__(self):
        return u'%s' % (self.name)
        
    @permalink
    def get_absolute_url(self):
        return ('portfolio.views.projects_by_discipline', [str(self.slug)])
        
class Program(models.Model):
    name = models.CharField(max_length=250)
    acronym = models.CharField(max_length=12)
    school = models.ForeignKey(Entity, blank=True, null=True)
    slug = models.SlugField(unique=True, help_text="Suggested value automatically generated from title. Must be unique.")
    
    def __unicode__(self):
        return u'%s' % (self.name)
  
class Studio(models.Model):
    """
    
    The studio at a school within which the project was completed.
    For use with an academic project.
    
    """
    SEMESTER_CHOICES = (
        ('Spring', 'Spring'),
        ('Fall', 'Fall'),
        ('Summer', 'Summer'),
        ('Winter', 'Winter'),
    )
    name = models.CharField(max_length=250)
    critic = models.ForeignKey(Person, blank=True, null=True) 
    program = models.ForeignKey(Program, blank=True, null=True)
    brief = models.TextField(blank=True)
    semester = models.CharField(max_length=6, choices=SEMESTER_CHOICES, blank=True)
    date = models.DateField()
    slug = models.SlugField(unique=True, help_text="Suggested value automatically generated from title. Must be unique.")
    
    def __unicode__(self):
        return u'%s' % (self.name)
        
class Competition(models.Model):
    """
    
        A design competition
    
    """
    name = models.CharField(max_length=250)
    sponsors = models.ManyToManyField(Entity)
    date = models.DateField()
    brief = models.TextField(blank=True)
    url = models.URLField(blank=True)
    slug = models.SlugField(unique=True, help_text="Suggested value automatically generated from title. Must be unique.")
    
    brief_html = models.TextField(blank=True, editable=False)

    def __unicode__(self):
        return u'%s' % (self.name)
    
    def save(self, force_insert=False, force_update=False):
        if self.brief:
            self.brief_html = markdown(self.brief)
        super(Competition, self).save(force_insert, force_update)

class Client(models.Model):
    CLIENT_MODELS = {'model__in':('person', 'entity')}
    order = PositionField(unique_for_field='project')
    project = models.ForeignKey("Project")
    
    content_type = models.ForeignKey(ContentType, limit_choices_to=CLIENT_MODELS)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type','object_id')

    def __unicode__(self):
        return u'%s' % (self.content_object)

    
class Collaborator(models.Model):
    order = PositionField(unique_for_field='project')
    person = models.ForeignKey(Person)
    project = models.ForeignKey("Project")
    
class Firm(models.Model):
    order = PositionField(unique_for_field='project')
    firm = models.ForeignKey(Entity)
    project = models.ForeignKey("Project")
    
class Project(models.Model):
    """
    
        A discrete design project.
    
    """
    objects = models.Manager() # The default manager.
    live = LiveProjectManager() # Only live projects.
    home = FeaturedHomeManager() # Live projects featured on home page
    work = FeaturedWorkManager() # Live projects featured on work page
    
    # project status choices 
    LIVE_STATUS = 1
    DRAFT_STATUS = 2
    HIDDEN_STATUS = 3
    STATUS_CHOICES = (
        (LIVE_STATUS, 'Live'),
        (DRAFT_STATUS, 'Draft'),
        (HIDDEN_STATUS, 'Hidden'),
    )
    
    # project context
    CONTEXT_CHOICES = (
        ('Professional', 'Professional'),
        ('Academic', 'Academic'),
        ('Personal', 'Personal'),
        ('Competition', 'Competition'),
    )
    
    # Core fields
    title = models.CharField(max_length=250)
    context = models.CharField("type", max_length=16, choices=CONTEXT_CHOICES)
    date = models.DateField()
    description = models.TextField()
    external_url = models.URLField(blank=True)
    
    # Categorization.
    disciplines = models.ManyToManyField(Discipline) 
    tags = TagField(help_text="Separate tags with spaces.")
    
    # genre specific fields
    studio = models.ForeignKey(Studio, blank=True, null=True)
    competition = models.ForeignKey(Competition, blank=True, null=True)
    
    # Fields to store generated HTML.
    description_html = models.TextField(editable=False, blank=True)
    
    # Metadata.
    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS, 
                                 help_text="Only projects with live status will be publicly displayed.")
    enable_comments = models.BooleanField(default=False)
    featured_home = models.BooleanField(default=False)
    featured_work = models.BooleanField(default=False)
    slug = models.SlugField(unique_for_date='date', help_text="Suggested value automatically generated from title. Must be unique.")
    
    creation_date = models.DateTimeField(auto_now_add=True, editable=False)
    modified_date = models.DateTimeField(auto_now=True, editable=False)
    
    class Meta:
        ordering = ('date','title',)
        
    def __unicode__(self):
        return u'%s' % (self.title)

    def save(self, force_insert=False, force_update=False):
        if self.description:
            self.description_html = markdown(self.description)
        super(Project, self).save(force_insert, force_update)

class ProjectFile(models.Model):
    project = models.ForeignKey(Project)
    lead = models.BooleanField(default=False)
    order = PositionField(unique_for_field='project')

    class Meta:
        abstract = True
        ordering = ['order']
        
    def save(self, *args, **kwargs):
        if self.lead:
            related_files = self._default_manager.filter(project=self.project)
            related_files.update(lead=False)
                
        return super(ProjectFile, self).save(*args, **kwargs) 
        
        
class ProjectVisual(ProjectFile):
    FILE_MODELS = {'model__in':('image', 'flash', 'video')}
    content_type = models.ForeignKey(ContentType, limit_choices_to=FILE_MODELS, 
                                     help_text="An image, animation, or video for this project.")
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type','object_id')

    def __unicode__(self):
        return u'%s' % (self.content_object)

class ProjectAudio(ProjectFile):
    audio = models.ForeignKey(Audio)
    
    def __unicode__(self):
        return u'%s' % (self.audio.title)
    
class ProjectDocument(ProjectFile):
    document = models.ForeignKey(Document)
    
    def __unicode__(self):
        return u'%s' % (self.document.title)
        
    
