"""
Field classes.
"""

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

__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):
        dur = value
        for f in self.formats:
            try:
                dur = time.strptime(dur, f)
                dur = dur.tm_hour*3600 + dur.tm_min*60 + dur.tm_sec
                dur = dur*1000
                break
            except:
                pass
        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'])
            