'''
Created on 05-09-2011

@author: lennyn
'''

from django.db.models import CharField, Model, IntegerField, TextField, ManyToManyField, ForeignKey
from helpers import bibtex2html, bibtex_utils, pdf_utils

class Person(Model):
    name = CharField(max_length=128, primary_key=True, db_index=True)
    
    def __unicode__(self):
        return self.name

class Keyword(Model):
    name = CharField(max_length=128, primary_key=True, db_index=True)
    
    def __unicode__(self):
        return self.name

class Publication(Model):
    id = CharField(max_length=100, primary_key=True)
    bibtex = TextField()
    crossref = ForeignKey('Publication', related_name='crossrefed_by', db_index=True, null=True)
    
    authors = ManyToManyField(Person, related_name='author_of', through='Authorship')
    editors = ManyToManyField(Person, related_name='editor_of', through='Editorship')
    title = CharField(max_length=100)
    year = IntegerField(null=True)
    abstract = TextField(null=True)
    keywords = ManyToManyField(Keyword)
    
    bibtex_html = TextField(null=True)
    
    def update_html(self):
        bibtex = bibtex_utils.get_bibtex4html(self.get_bibtex(), self.id)
        self.bibtex_html = bibtex2html.bibtex2html(bibtex)
    
    def update_url_in_bibtex(self):
        bib_data = bibtex_utils.get_bib_data(self.bibtex)
        assert len(bib_data.entries) == 1
        entry = bib_data.entries[self.id]
        
        if pdf_utils.uploaded_file_exists(self.id):
            entry.fields['url'] = pdf_utils.pubid2url(self.id)
        elif entry.fields.get('url', '') == pdf_utils.pubid2url(self.id):
            del entry.fields['url']
        
        self.bibtex = bibtex_utils.get_bibtex_text(self.id, entry)
        self.update_html()
    
    def get_html(self):
        return self.bibtex_html
    
    def get_bibtex(self, resolve_crossref=True):
        res = [self.bibtex]
        if resolve_crossref and self.crossref:
            res.append(self.crossref.get_bibtex())
        return u'\n'.join(res)

class PersonPublicationRelation(Model):
    person = ForeignKey(Person, db_index=True)
    publication = ForeignKey(Publication, db_index=True)
    idx = IntegerField(db_index=True)
    
    class Meta:
        unique_together = (
                           ('person', 'publication'),
                           ('publication', 'idx'),
                           )
        abstract = True

class Authorship(PersonPublicationRelation):
    pass

class Editorship(PersonPublicationRelation):
    pass
