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, create_empty_iri
import os
import os.path
import uuid
import xml

class Author(models.Model):

    handle = models.CharField(max_length=512, unique=True, blank=True, null=True)
    email = models.EmailField(unique=False, blank=True, null=True)
    firstname = models.CharField(max_length=512, blank=True, null=True)
    lastname = models.CharField(max_length=512, blank=True, null=True)
    
    def __unicode__(self):
        return unicode(self.id) + " - " + self.handle + ", " + self.email + ", " + self.firstname + " " + self.lastname


class Content(models.Model):
    iri_id = models.CharField(max_length=1024, unique=True)
    iriurl = models.CharField(max_length=1024)
    src = models.CharField(max_length=1024)
    videopath = models.CharField(max_length=1024, 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, blank=True)
    duration = models.IntegerField(null=True, blank=True)

    def get_duration(self):
        if self.duration is None:
            doc = xml.dom.minidom.parse(self.iri_file_path())
            doc = Ft.Xml.Domlette.ConvertDocument(doc)        
            con = xml.xpath.Context.Context(doc, 1, 1, None)
            res = xml.xpath.Evaluate("/iri/body/medias/media[@id='video']/video", context=con)
            self.duration = int(res[0].getAttributeNS(None, u'dur'))
            self.save()
        return self.duration
    
    def delete(self):
        super(Content, self).delete()
        writer = lucene.IndexWriter(STORE, ANALYZER, True, lucene.IndexWriter.MaxFieldLength.UNLIMITED)
        writer.deleteDocuments(lucene.Term("iri_id", self.iri_id))
        writer.commit()
        
    def save(self):
        # create iri file if needed
        try:
            iri_file_path = self.iri_file_path()
            if not os.path.exists(iri_file_path):
                dir = os.path.dirname(iri_file_path)
                if not os.path.exists(dir):
                    os.makedirs(dir)
                file = open(iri_file_path,"w")
                create_empty_iri(file, self, "IRI")
        except Exception, e:
            if os.path.exists(iri_file_path):
                os.remove(iri_file_path)
                raise e
        # update it 
        super(Content, self).save()
    
    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)
    
    def iri_file_path(self):
        return os.path.join(os.path.join(os.path.join(os.path.join(settings.MEDIA_ROOT, "media"), "ldt"), self.iri_id), os.path.basename(self.iriurl))

    def iri_url_template(self):
        return "${web_url}${media_url}media/ldt/" + unicode(self.iri_id) + "/" + os.path.basename(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)
    
    def get_description(self, doc=None):
        
        if doc is None:
            doc = xml.dom.minidom.parseString(self.ldt)
            doc = Ft.Xml.Domlette.ConvertDocument(doc)        
        
        con = xml.xpath.Context.Context(doc, 1, 1, None)
        res = xml.xpath.Evaluate("/iri/project", context=con)
        if len(res) > 0:
            return res[0].getAttributeNS(None, u'abstract')
        else:
            return None
        

    @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

class Segment(models.Model):
    
    project_obj = models.ForeignKey(Project, null=True)
    content = models.ForeignKey(Content)
    project_id = models.CharField(max_length=1024, unique=False, blank=True, null=True)
    iri_id = models.CharField(max_length=1024, unique=False)
    ensemble_id = models.CharField(max_length=1024, unique=False)
    cutting_id = models.CharField(max_length=1024, unique=False)    
    element_id = models.CharField(max_length=1024, unique=False)
    tags = models.CharField(max_length=2048, unique=False, null=True, blank=True)  
    title = models.CharField(max_length=2048, unique=False, null=True, blank=True)
    duration = models.IntegerField(null=True)
    start_ts = models.IntegerField(null=True)
    author = models.CharField(max_length=1024, unique=False, null=True, blank=True)
    date = models.CharField(max_length=128, unique=False, null=True, blank=True)
    abstract = models.TextField(null=True, blank=True)
    
    def __unicode__(self):
        return "/".join((unicode(self.project_id), unicode(self.iri_id), unicode(self.ensemble_id), unicode(self.cutting_id), unicode(self.element_id)))
    
    class Meta:
        unique_together = (('project_id', 'iri_id', 'ensemble_id', 'cutting_id', 'element_id'),)

