from django.db import models
from django.conf import settings
from ldt.core.models import Document, Owner
from django.utils.translation import ugettext_lazy as _
from utils import create_ldt, copy_ldt
import uuid

class Content(models.Model):
    iri_id = models.CharField(max_length=1024, unique=True)
    iriurl = models.URLField()
    videopath = models.URLField(null=True, blank=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=1024, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    external_id = models.CharField(max_length=1024, null=True, blank=True)
    # authors = models.ManyToManyField(Author)
    
    def __unicode__(self):
        return str(self.id) + ": " + self.iri_id
        
    def iri_url(self, web_url=settings.WEB_URL):
        if 'http' in self.iriurl or 'https' in self.iriurl:
            return self.iriurl
        else:
            return unicode(web_url) + unicode(settings.MEDIA_URL)+u"media/ldt/"+unicode(self.iriurl)
        
        
class Project(Document):  
    STATE_CHOICES=(
    (1, 'edition'),
    (2, 'published'),
    (3, 'moderated'),
    (4, 'rejected'),
    (5, 'deleted')
    )
    ldt_id = models.CharField(max_length=1024, unique=True)
    ldt = models.TextField(null=True)
    title = models.CharField(max_length=1024)
    contents = models.ManyToManyField(Content)
    creation_date = models.DateTimeField(auto_now_add=True)
    modification_date = models.DateTimeField(auto_now=True)
    created_by = models.CharField(_("created by"), max_length=70)
    changed_by = models.CharField(_("changed by"), max_length=70)
    state = models.IntegerField(choices=STATE_CHOICES, default=1)
    
    def __unicode__(self):
        return unicode(self.id) + u": " + unicode(self.ldt_id)

    @staticmethod
    def create_project(user, title, contents):
        owner = Owner.objects.get(user=user)
        project = Project(title=title, owner=owner)
        project.ldt_id = str(uuid.uuid1())
        project.created_by=user.username
        project.changed_by=user.username
        project.state = 1
        project.save()
        for content in contents:
            project.contents.add(content)
        project.save()
        return create_ldt(project, user)

    def copy_project(self, user, title):
        owner = Owner.objects.get(user=user)
        project = Project(title=title, owner=owner)
        project = copy_ldt(self, project, user)
        project.save()
        for content in self.contents.all():
            project.contents.add(content)
        project.save()
        return project

