# https://github.com/mfenniak/pyPdf
from collections import defaultdict

from pyPdf import PdfFileReader
from pyPdf.utils import PyPdfError

from ..base.models import Request
from ..utils import cache_to_django

def fill_document_attributes_from_pdf_file(document, docfile):
    try:
        if docfile:
            pdf_file = PdfFileReader(docfile)
            pdf_info = pdf_file.documentInfo
            attrs = ['/Title', '/Subject']
            titles = map(unicode, filter(None, map(lambda attr: pdf_info.get(attr), attrs)))
            document.name = u' - '.join(titles)
            document.nb_pages = pdf_file.numPages
    except PyPdfError:
        raise ValueError(u"Vous ne pouvez envoyer que des fichiers PDF.")

@cache_to_django(timeout=300)
def field_completion(user, field_names, without_scores=True):
    qs = Request.objects.filter(user=user)
    scores = defaultdict(lambda: defaultdict(lambda: 0))
    for values in qs.values_list(*field_names):
        for field_name, value in zip(field_names, values):
            if value is not None:
                scores[field_name][value] += 1
    for key, value in scores.iteritems():
        scores[key] = sorted(scores[key].items(), key=lambda x: x[1])
        if without_scores:
            scores[key] = map(lambda x: x[0], scores[key])
        scores[key] = scores[key][:3] + sorted(scores[key][3:])
    return scores

