import os

from django.db import models
from django.contrib import admin
import lucene
from pocketfilms.ldt import STORE
from pocketfilms.ldt import ANALYZER
from pocketfilms 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)
    
    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)
    
    
admin.site.register(Content)
admin.site.register(Author)
admin.site.register(LdtProject)

