from django.template.defaultfilters import slugify
from django import template
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _


from .. import models
from .. import app_settings

register = template.Library()

def paginator(context):
    """
    To be used in conjunction with the object_list generic view.

    Adds pagination context variables for use in displaying first, adjacent and
    last page links in addition to those created by the object_list generic
    view.

    """
    page = context['page']
    hits = page.paginator.count
    pn = page.number
    link_to_last_page = (page.paginator.num_pages > 2) and (pn < (page.paginator.num_pages-1))
    return {
        'hits': hits,
        'page_number': page.number,
        'link_to_last_page': link_to_last_page,
        'last_page': page.paginator.num_pages,
        'first': page.start_index(),
        'last': page.end_index(),
        'previous': page.number-1,
        'next': page.number+1,
        'has_next': page.has_next(),
        'has_previous': page.has_previous(),
    }

register.inclusion_tag('docbow/paginator.html', takes_context=True)(paginator)

def menu(context):
    here = context.get('view_name')
    docbow_menu = []
    for view_name, caption in app_settings.DOCBOW_MENU:
        count = 0
        current = False
        if view_name == 'inbox':
            count = models.Mailbox.objects.filter(
                        owner=context['user'],
                        deleted=False,
                        seen=False,
                        outbox=False).count()
        # remove delegation view for guest accounts
        if models.is_guest(context['user']) and 'delegate' in view_name:
            continue
        if view_name.startswith('docbow_admin:') and not context['user'].is_staff:
            continue
        if view_name == here:
            current = True
        if view_name.startswith('http'):
            url = view_name
            view_name = slugify(view_name)
        else:
            url = reverse(view_name)
        docbow_menu.append({ 'view_name': view_name.replace(':', '-'),
            'url': url, 'caption': caption, 'count': count,
            'current': current})
    return { 'menus': docbow_menu }

register.inclusion_tag('docbow/menu.html', takes_context=True)(menu)

def username(value):
    return models.username(value)
register.filter(username)

def doc_real_sender(document):
    return document.real_sender or models.username(document.sender)
register.filter(doc_real_sender)

def frfilesizeformat(value):
    if value < 1024*1024:
        value = value / 1024.0
        unit = _('kB')
    else:
        value = value / (1024*1024.0)
        unit = _('MB')
    return "%.1f %s" % (value, unit)

register.filter(frfilesizeformat)

def humantargets(value):
    user_human_to = value.user_human_to()
    group_human_to = value.group_human_to()
    l1 = map(lambda x: _('to %s') % x, user_human_to)
    if len(user_human_to) > 1:
        p1 = _('%(one)s and %(two)s') % { 'one': ', '.join(l1[0:-1]), 'two': l1[-1] }
    elif user_human_to:
        p1 = l1[0]
    l2 = map(lambda x: _('to list %s') % x, group_human_to)
    if len(group_human_to) > 1:
        p2 = _('%(one)s and %(two)s') % { 'one': ', '.join(l2[0:-1]), 'two': l2[-1] }
    elif group_human_to:
        p2 = l2[0]
    if l1 and l2:
        return _('%(one)s and to lists %(two)s') % { 'one': p1, 'two': p2 }
    elif l1:
        return p1
    elif l2:
        return p2
    else:
        return ''

register.filter(humantargets)

def nonbreakinghyphen(value):
    return value.replace('-', '&#8209;')

register.filter(nonbreakinghyphen)



def ellipsizedfilename(value, length=25):
    if len(value) > length:
        value = value[:length] + '&#8230;'
    return value

register.filter(ellipsizedfilename)

@register.filter_function
def order_by(queryset, args):
    args = [x.strip() for x in args.split(',')]
    return queryset.order_by(*args)
