'''
Created on 15-10-2011

@author: lennyn
'''
import locale
import urlparse
from pybtex.core import Person
from django.utils.encoding import smart_str

locale.setlocale(locale.LC_ALL, "")

def group_pubs_by_year(pubs):
    res = {}
    for pub in pubs:
        res.setdefault(pub.year, [])
        res[pub.year].append(pub)
    return res

def sort_pubs_by_author(pubs):
    return sorted(pubs, key=_get_publication_sort_key)

def _get_publication_sort_key(pub):
    authors = pub.authors.order_by('authorship__idx')
    editors = pub.editors.order_by('editorship__idx')
    return (
            tuple([_get_one_author_sort_key(Person(a.name)) for a in list(authors) + list(editors)]),
            pub.year,
            pub.title)

def _get_one_author_sort_key(a):
    return locale.strxfrm(smart_str(unicode(a)))

def get_domain(url):
    parse = urlparse.urlparse(url)
    domain = parse.netloc
    if parse.scheme:
        domain = parse.scheme + '://' + domain
    return domain
