from django import forms

import timer.models


class OfficeHoursForm(forms.ModelForm):
    class Meta:
        model = timer.models.OfficeHours
        fields = ['user', 'begins_at', 'ends_at']

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        return super().__init__(*args, **kwargs)

    def full_clean(self):
        if not self.user.is_authenticated:
            raise forms.ValidationError('Invalid User.')
        return

    def save(self):
        begins_at = timer.models.OfficeHours.parse_time_str(self.data.get('begins_at'))
        user = self.user
        obj = timer.models.OfficeHours.objects.create(
            user=user, begins_at=begins_at, ends_at=timer.models.OfficeHours.get_ends_at(begins_at)
        )
        return obj
