'''
Created on 13-10-2011

@author: lennyn
'''
import os
import re
from bibmate import settings
from bibmate.helpers.publist_utils import get_domain
from django.core.urlresolvers import reverse

UPLOADS_ROOT = os.path.join(settings.MEDIA_ROOT, 'pdf')
UPLOADS_URL = os.path.join(settings.MEDIA_URL, 'pdf')

def handle_uploaded_file(f, pub_id):
    if not os.path.isdir(UPLOADS_ROOT):
        os.makedirs(UPLOADS_ROOT)
    filepath = pubid2filepath(pub_id)
    destination = open(filepath, 'wb+')
    try:
        for chunk in f.chunks():
            destination.write(chunk)
    finally:
        destination.close()
    
#   pybtex_utils.add_pdf_url(pub_id, url)

def uploaded_file_exists(pub_id):
    return os.path.isfile(pubid2filepath(pub_id))

def delete_uploaded_file(pub_id):
    filepath = pubid2filepath(pub_id)
    if os.path.isfile(filepath):
        os.remove(filepath)

def pubid2filepath(pub_id):
    return os.path.join(UPLOADS_ROOT, pubid2filename(pub_id))

def pubid2filename(pub_id):
    return pub_id.replace(':', '_') + '.pdf'

#def filename2pubid(pubfilename):
#   return re.sub(r'\.pdf$', '', pubfilename.replace('_', ':'))

def pubid2url(pub_id):
    #~ print settings.ROOT_URL, reverse('download', args=[pub_id])
    return get_domain(settings.ROOT_URL) + reverse('download', args=[pub_id])
