from django.template import Library, TemplateSyntaxError

register = Library()

@register.filter
def to_hours(value, arg=None):
    """Takes an integer value of milliseconds and write the hour duration"""
    # 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
    return (sec//3600)
to_hours.is_safe = True


@register.filter
def to_minutes(value, arg=None):
    """Takes an integer value of milliseconds and write the hour duration"""
    # 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
    hours = sec//3600
    min = (sec - (hours * 3600))//60
    return min
to_minutes.is_safe = True


@register.filter
def to_seconds(value, arg=None):
    """Takes an integer value of milliseconds and write the hour duration"""
    # 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
    hours = sec//3600
    min = (sec - (hours * 3600))//60
    sec = (sec - (hours * 3600) - (min*60))
    return sec
to_seconds.is_safe = True

