from django import template
from time import strftime
import dateutil.parser

register = template.Library()

def strfdelta(tdelta):
    minutes,seconds = divmod(tdelta.seconds,60)
    tenths = int(tdelta.microseconds/1e5)
    res = "{minutes:0>1}:{seconds:0>2}.{tenths:0>1}".format(
	minutes=minutes,
	seconds=seconds,
	tenths=tenths,
	)
    
    return res

def strfdeltah(tdelta):
    hours, rest = divmod(tdelta.seconds,3600)
    minutes,seconds = divmod(rest,60)
    tenths = int(tdelta.microseconds/1e5)
    res = "{hours:0>2}:{minutes:0>2}:{seconds:0>2}.{tenths:0>1}".format(
	hours=hours,
	minutes=minutes,
	seconds=seconds,
	tenths=tenths,
	)
    
    return res

def secondstotimestring(tdelta):
    hours, rest = divmod(tdelta,3600)
    minutes,seconds = divmod(rest,60)
    res = "{hours:0>2}:{minutes:0>2}:{seconds:0>2}".format(
	hours=hours,
	minutes=minutes,
	seconds=seconds,
	)
    
    return res

@register.filter
def durationprint(d,dstring):
    if (d == None):
	return d
    else:
	return d.strftime(dstring)[:-5]

@register.filter
def paceprint(d):
    if (d == None):
	return d
    else:
	return strfdelta(d)

@register.filter
def deltatimeprint(d):
    if (d == None):
	return d
    else:
	return strfdeltah(d)


@register.filter
def lookup(dict, key):
    s = dict.get(key)
    
    if isinstance(s,basestring) and len(s) > 22:
	s = s[:22]
    return s

@register.filter
def ualookup(dict, key):
    s = dict.get(key)

    if key=='distance':
        s = int(float(s))

    if key=='duration':
        s = secondstotimestring(int(s))
        

    if key=='starttime':
        s = dateutil.parser.parse(s)
        
    return s

@register.filter(name='times')
def times(number):
    return range(number)

@register.simple_tag
def get_field_id(id,s,form):
    field_name = s+str(id)
    return form.__getitem__(field_name)

from rowers.models import Rower,Team

@register.filter
def is_manager(user):
    r = Rower.objects.get(user=user)
    return r.rowerplan == 'coach'

@register.filter
def user_teams(user):
    try:
        therower = Rower.objects.get(user=user)
        teams1 = therower.team.all()
        teams2 = Team.objects.filter(manager=user)
        teams = list(set(teams1).union(set(teams2)))
    except TypeError:
        teams = []

    return teams

@register.filter
def has_teams(user):
    try:
        therower = Rower.objects.get(user=user)
        teams1 = therower.team.all()
        teams2 = Team.objects.filter(manager=user)
        teams = list(set(teams1).union(set(teams2)))
        return True
    except TypeError:
        return False

    return False

@register.filter
def team_members(user):
    try:
        therower = Rower.objects.get(user=user)
        if therower.rowerplan != 'coach':
            return []
        teams = Team.objects.filter(manager=user)
        members = Rower.objects.filter(team__in=teams)
        return [rower.user for rower in members]
    except TypeError:
        return []

    return []
