"""
Field classes.
"""

from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
import logging
import time
import math

__all__ = (
    'LdtDurationField'
)

class LdtDurationField (forms.TimeField):
    """
    A field allowing to enter the duration format (eg: XhMM, XXhMM, HH:MM:SS)
    """
    
    default_error_messages = {
        'required': _(u'The duration field can not be empty.'),
        'invalid': _(u'Enter a valid duration format;'),
    }
    
    def __init__(self, formats, *args, **kwargs):
        self.formats = formats
        super(LdtDurationField, self).__init__(*args, **kwargs)
    
    def to_python(self, value):
        logging.debug(value)
        dur = value
        for format in self.formats:
            try:
                dur = time.strptime(dur, format)
                dur = dur.tm_hour*3600 + dur.tm_min*60 + dur.tm_sec
                dur = dur*1000
                break
            except:
                logging.debug("trying next format")
        logging.debug(str(dur))
        return dur
    
    def validate(self, value):
        if value==None or value=="":
            raise ValidationError(self.default_error_messages['required'])
        else:
            try:
                int(value)
            except (ValueError, TypeError):
                raise ValidationError(self.default_error_messages['invalid'])
            