from django import template
from django.utils.safestring import mark_safe
from time import strftime
import dateutil.parser
import json
import datetime
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 ddays(ddelta):
    return ddelta.days+1

@register.filter
def spacetohtml(t):
    return t.replace(" ","%20")

@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(is_safe=True)
def jsdict(dict,key):
    s = dict.get(key)
    return mark_safe(json.dumps(s))
    
@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

from rowers.views import ispromember
@register.filter
def is_promember(user):
    return ispromember(user)

@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).distinct()
        return [rower.user for rower in members]
    except TypeError:
        return []

    return []

@register.filter
def team_rowers(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).distinct()
        return members
    except TypeError:
        return []

    return []

@register.filter
def verbosetimeperiod(timeperiod):
    table = {
        'today':'Today',
        'thisweek': 'This Week',
        'thismonth': 'This Month',
        'lastmonth': 'Last Month',
        'lastweek': 'Last Week',
        }

    try:
        verbose = table[timeperiod]
    except KeyError:
        verbose = timeperiod

    return verbose
        
from datetime import date

@ register.filter
def future_date_only(the_date):
    if the_date > date.today():
        return the_date
    else:
        return None


@register.filter
def is_future_date(the_date):
    return the_date >= date.today()

@register.filter
def date_dif(the_date):
    if the_date:
        return the_date - date.today()
    else:
        return 1

    
