import os
import xml
import Ft.Xml.Domlette

from django.db import models
from django.contrib import admin
import lucene
from blinkster.ldt import STORE
from blinkster.ldt import ANALYZER
from blinkster import settings

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):

    def uploadTo(self, filename):
        return "media/ldt/" + self.iri_id + "/" + filename

    iri_id = models.CharField(max_length=1024, unique=True)
    iri = models.FileField(upload_to=uploadTo, null=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=1024, null=True)
    description = models.TextField(null=True)
    external_id = models.CharField(max_length=1024, null=True, blank=True)
    authors = models.ManyToManyField(Author)
    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, 'dur'))
            self.save()
        return self.duration
    
    def delete(self):
        super(Content, self).delete()
        writer = lucene.IndexModifier(STORE, ANALYZER, True)
        writer.deleteDocuments(lucene.Term("iri_id", self.iri_id))
        writer.flush()
    
    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.iri.path))

    def iri_url(self, web_url=""):
        return unicode(web_url) + unicode(settings.MEDIA_URL) + u"media/ldt/" + unicode(self.iri_id) + "/" + os.path.basename(self.iri.path)

    def iri_url_template(self):
            return "${web_url}${media_url}media/ldt/" + unicode(self.iri_id) + "/" + os.path.basename(self.iri.path)
    
    def __unicode__(self):
        return str(self.id) + ": " + self.iri_id

    
class LdtProject(models.Model):
    
    ldt_id = models.CharField(max_length=1024, unique=True)
    ldt = models.TextField(null=True)
    authors = models.ManyToManyField(Author)
    contents = models.ManyToManyField(Content)
    creation_date = models.DateTimeField(auto_now_add=True)
    modification_date = models.DateTimeField(auto_now=True)
    
    def __unicode__(self):
        return unicode(self.id) + u": " + unicode(self.ldt_id)

class Segment(models.Model):
    
    project_obj = models.ForeignKey(LdtProject, 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'),)
    
    
admin.site.register(Content)
admin.site.register(Author)
admin.site.register(LdtProject)
admin.site.register(Segment)

