# -*- Mode: Python; -*-
# -*- coding: utf-8 -*-
# vi:si:et:sw=2:sts=2:ts=2

from model import SortName


articles=('the', 'der', 'die', 'das', 'le', 'la', "l'")

'''
  internal function to generate the sortname, only called if name not in 
  blacklist
'''
def _sortname(name):
  names = name.split(' ')
  len_names = len(names)
  if names[0].lower() in articles:
    names.append(names.pop(0))
    len_names -= 1
  if len_names > 1:
    last_name = names.pop(len_names - 1)
    names = (last_name, " ".join(names))
  return ", ".join(names)

'''
  returns a sortname for name
'''
def sortname(name):
  q = SortName.select(SortName.q.name == name)
  if q.count() == 0:
    return _sortname(name)
  else:
    return name