from flask_restful import abort


class DatetimeFilterMixin(object):

    def validate_get_feed_request(self, qs):
        """
        Validate:
        * If there is a datetime__to argument, there must be a datetime__from
        * Future content is not a valid argument
        * User can only filter by one datetime filter
          + publication_datetime
          + last_modified_datetime
          + meta.last_update
        """

        if qs.publication_datetime__to and not qs.publication_datetime__from:
            abort(400, message='Missing query argument '
                               'publication_datetime__from')

        if qs.last_modified_datetime__to and not qs.last_modified_datetime__from:
            abort(400, message='Missing query argument '
                               'last_modified_datetime__from')

        if qs.get('meta.last_update__to') and not qs.get('meta.last_update__from'):
            abort(400, message='Missing query argument '
                               'meta.last_update__from')

        if qs.future_content:
            abort(400, message='The parameter future_content is invalid')

        if not self.verify_date_arguments(qs, ['publication_datetime',
                                               'last_modified_datetime',
                                               'meta.last_update']):
            abort(400, message='Only one datetime parameter is valid')

    @staticmethod
    def verify_date_arguments(qs, arguments):
        """
        Verify that there is only one datetime based filter 
        """
        datetime_query = False

        for argument in arguments:
            if qs[argument] or qs[argument + '__from'] or qs[argument + '__to']:
                if not datetime_query:
                    datetime_query = True
                else:
                    return False
        return True
