# -*- coding: utf-8 -*-
'''
Created on Nov 12, 2012

@author: ymh
'''
# -*- coding: utf-8 -*-
'''
Created on Nov 12, 2012

@author: ymh
'''


from django.template import Library, TemplateSyntaxError

register = Library()

@register.filter
def str_duration(value, arg=None):
    """Takes an integer value of milliseconds and write a human readable duration like 1h23, 01:23 (hours:minutes), 01:23:45 (hours:minutes:seconds), or number of seconds """
    # Error management
    if value is None :
        return ""
    if not isinstance(value, (int,long,float,str,unicode)) :
        raise TemplateSyntaxError('str_duration value error : value must be integer or long or float or string. type = ' + str(type(value)))
    if isinstance(value, (str,unicode)) :
        try:
            value = int(value)
        except :
            raise TemplateSyntaxError('str_duration value error : can not convert value "' + value + '" into integer')
    # We take off the milliseconds
    ms = abs(value)
    sec = ms//1000
    if arg is None :
        arg = "::"
    if arg=="::" or arg=="h" or arg==":" :
        hours = sec//3600
        min_val = (sec - (hours * 3600))//60
        if min_val<10:
            min_str = "0" + str(min_val)
        else:
            min_str = str(min_val)
        if (arg=="::" or arg==":") and hours<10 :
            hours_str = "0" + str(hours)
        else :
            hours_str = str(hours)
        if arg=="h" or arg==":" :
            return hours_str + arg + min_str
        sec = (sec - (hours * 3600) - (min_val*60))
        if sec<10:
            sec_str = "0" + str(sec)
        else:
            sec_str = str(sec)
        return hours_str + ":" + min_str + ":" + sec_str
    elif arg=="s" :
        return sec
    else :
        raise TemplateSyntaxError('str_duration filter error : filters argument must be None, "::", ":", "h" or "s"')
str_duration.is_safe = True

@register.filter
def get_range(value):
    return range(value)

@register.filter
def list2str(value):
    return ("%s"%value)[1:-1]
