from datetime import datetime, timedelta

from django.forms import forms, fields


class CreateLentaReportForm(forms.Form):
    date_from = fields.DateField(
        required=False,
        input_formats=tuple(fields.DateField.input_formats) + ('%d.%m.%Y',)
    )
    date_to = fields.DateField(
        required=False,
        input_formats=tuple(fields.DateField.input_formats) + ('%d.%m.%Y',)
    )
    limit = fields.IntegerField(required=False)
    offset = fields.IntegerField(required=False)

    def clean(self):
        cd = self.cleaned_data
        date_limit = None
        date_offset = None
        today = datetime.today().date()

        date_from = cd['date_from']
        date_to = cd['date_to'] or today

        offset = cd['offset'] or 0
        limit = cd.get('limit')

        if limit:
            date_offset = today - timedelta(days=offset)
            date_limit = date_offset - timedelta(days=limit)

        date_from = (
            max(date_from, date_limit)
            if date_from and date_limit
            else date_from or date_limit
        )

        date_to = (
            min(date_to, date_offset)
            if date_to and date_offset
            else date_to or date_offset
        )

        if not (date_from and date_to):
            self._errors['__all__'] = self.error_class(
                ['either date_from or limit is required'])
            return {}

        if date_from > date_to:
            self._errors['date_from'] = self.error_class(['wrong_date_from'])

        return {
            'date_from': date_from,
            'date_to': date_to,
        }
