'''
Created on 07-09-2011

@author: lennyn
'''
import os
import tempfile
import subprocess
import codecs

from bibmate import settings

def bibtex2html(bibtex):
    bib_fname = _maketemp(suffix='.bib')
    html_fname = _maketemp(suffix='.html')
    f = codecs.open(bib_fname, 'w', 'utf-8')
    f.write(_correctBibtex(bibtex))
    f.close()
    pdfImgLink = settings.STATIC_URL + 'img/pdficon_small.png'
    subprocess.check_call(
                    [
                        settings.BIB2HTML_PATH, 
                        '-cru', 
                        '-s', 'paragraph', 
                        '-e', 'nobrackets,PDF:<img src="%s" alt="PDF" border="0" />' % pdfImgLink, 
                        bib_fname, 
                        html_fname
                    ], 
                    cwd=os.path.dirname(settings.BIB2HTML_PATH),
                    stderr=subprocess.PIPE)
    f = codecs.open(html_fname, 'r', 'utf-8')
    res = f.read()
    f.close()
    subprocess.check_call(['rm', bib_fname, html_fname])
    return res

def _correctBibtex(bibtex):
    return u'\n'.join([_correctLine(line) for line in bibtex.split('\n')])

def _correctLine(line):
    if line.strip().startswith('author'):
        return line.replace('[', '').replace(']', '')
    else:
        return line
    
def _maketemp(suffix='', prefix='bibmate_'):
    fd, fname = tempfile.mkstemp(suffix=suffix, prefix=prefix)
    os.close(fd)
    return fname
