# Path: advanced_filters/models.py
# class AdvancedFilter(models.Model):
#     class Meta:
#         verbose_name = _('Advanced Filter')
#         verbose_name_plural = _('Advanced Filters')
# 
#     title = models.CharField(max_length=255, null=False, blank=False, verbose_name=_('Title'))
#     created_by = models.ForeignKey(
#         settings.AUTH_USER_MODEL,
#         related_name='created_advanced_filters',
#         verbose_name=_('Created by'),
#         on_delete=models.CASCADE,
#     )
#     created_at = models.DateTimeField(auto_now_add=True, null=True, verbose_name=_('Created at'))
#     url = models.CharField(max_length=255, null=False, blank=False, verbose_name=_('URL'))
#     users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, verbose_name=_('Users'))
#     groups = models.ManyToManyField('auth.Group', blank=True, verbose_name=_('Groups'))
# 
#     objects = UserLookupManager()
# 
#     b64_query = models.CharField(max_length=2048)
#     model = models.CharField(max_length=64, blank=True, null=True)
# 
#     @property
#     def query(self):
#         """
#         De-serialize, decode and return an ORM query stored in b64_query.
#         """
#         if not self.b64_query:
#             return None
#         s = QSerializer(base64=True)
#         return s.loads(self.b64_query)
# 
#     @query.setter
#     def query(self, value):
#         """
#         Serialize an ORM query, Base-64 encode it and set it to
#         the b64_query field
#         """
#         if not isinstance(value, Q):
#             raise Exception('Must only be passed a Django (Q)uery object')
#         s = QSerializer(base64=True)
#         self.b64_query = s.dumps(value)
# 
#     def list_fields(self):
#         s = QSerializer(base64=True)
#         d = s.loads(self.b64_query, raw=True)
#         return s.get_field_values_list(d)
# 
# Path: advanced_filters/form_helpers.py
# class CleanWhiteSpacesMixin:
#     """
#     This mixin, when added to any form subclass, adds a clean method which
#     strips repeating spaces in and around each string value of "clean_data".
#     """
#     def clean(self):
#         """
#         >>> import django.forms
#         >>> class MyForm(CleanWhiteSpacesMixin, django.forms.Form):
#         ...     some_field = django.forms.CharField()
#         >>>
#         >>> form = MyForm({'some_field': ' a   weird value  '})
#         >>> assert form.is_valid()
#         >>> assert form.cleaned_data == {'some_field': 'a weird value'}
#         """
#         cleaned_data = super().clean()
#         for k in self.cleaned_data:
#             if isinstance(self.cleaned_data[k], str):
#                 cleaned_data[k] = re.sub(extra_spaces_pattern, ' ',
#                                          self.cleaned_data[k] or '').strip()
#         return cleaned_data
# 
# class VaryingTypeCharField(forms.CharField):
#     """
#     This CharField subclass returns a regex OR patterns from a
#     comma separated list value.
#     """
#     _default_separator = ","
# 
#     def to_python(self, value):
#         """
#         Split a string value by separator (default to ",") into a
#         list; then, returns a regex pattern string that ORs the values
#         in the resulting list.
# 
#         >>> field = VaryingTypeCharField()
#         >>> assert field.to_python('') == ''
#         >>> assert field.to_python('test') == 'test'
#         >>> assert field.to_python('and,me') == '(and|me)'
#         >>> assert field.to_python('and,me;too') == '(and|me;too)'
#         """
#         res = super().to_python(value)
#         split_res = res.split(self._default_separator)
#         if not res or len(split_res) < 2:
#             return res.strip()
# 
#         # create a regex string out of the list of choices passed, i.e: (a|b)
#         res = r"({pattern})".format(pattern="|".join(
#             map(lambda x: x.strip(), split_res)))
#         return res


from datetime import datetime as dt
from pprint import pformat
from django import forms
from django.apps import apps
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.utils import get_fields_from_path
from django.core.exceptions import FieldDoesNotExist
from django.db.models import Q
from django.db.models.fields import DateField
from django.forms.formsets import formset_factory, BaseFormSet
from functools import reduce
from django.utils.text import capfirst
from django.utils.translation import gettext_lazy as _
from .models import AdvancedFilter
from .form_helpers import CleanWhiteSpacesMixin,  VaryingTypeCharField
import logging
import operator
            self.fields['field'].initial = self.FIELD_CHOICES[0]


class AdvancedFilterFormSet(BaseFormSet):
    """ """
    fields = ()
    extra_kwargs = {}

    def __init__(self, *args, **kwargs):
        self.model_fields = kwargs.pop('model_fields', {})
        super().__init__(*args, **kwargs)
        if self.forms:
            form = self.forms[0]
            self.fields = form.visible_fields()

    def get_form_kwargs(self, index):
        kwargs = super().get_form_kwargs(index)
        kwargs['model_fields'] = self.model_fields
        return kwargs


AFQFormSet = formset_factory(
    AdvancedFilterQueryForm, formset=AdvancedFilterFormSet,
    extra=1, can_delete=True)

AFQFormSetNoExtra = formset_factory(
    AdvancedFilterQueryForm, formset=AdvancedFilterFormSet,
    extra=0, can_delete=True)



# Path: advanced_filters/models.py
# class AdvancedFilter(models.Model):
#     class Meta:
#         verbose_name = _('Advanced Filter')
#         verbose_name_plural = _('Advanced Filters')
# 
#     title = models.CharField(max_length=255, null=False, blank=False, verbose_name=_('Title'))
#     created_by = models.ForeignKey(
#         settings.AUTH_USER_MODEL,
#         related_name='created_advanced_filters',
#         verbose_name=_('Created by'),
#         on_delete=models.CASCADE,
#     )
#     created_at = models.DateTimeField(auto_now_add=True, null=True, verbose_name=_('Created at'))
#     url = models.CharField(max_length=255, null=False, blank=False, verbose_name=_('URL'))
#     users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, verbose_name=_('Users'))
#     groups = models.ManyToManyField('auth.Group', blank=True, verbose_name=_('Groups'))
# 
#     objects = UserLookupManager()
# 
#     b64_query = models.CharField(max_length=2048)
#     model = models.CharField(max_length=64, blank=True, null=True)
# 
#     @property
#     def query(self):
#         """
#         De-serialize, decode and return an ORM query stored in b64_query.
#         """
#         if not self.b64_query:
#             return None
#         s = QSerializer(base64=True)
#         return s.loads(self.b64_query)
# 
#     @query.setter
#     def query(self, value):
#         """
#         Serialize an ORM query, Base-64 encode it and set it to
#         the b64_query field
#         """
#         if not isinstance(value, Q):
#             raise Exception('Must only be passed a Django (Q)uery object')
#         s = QSerializer(base64=True)
#         self.b64_query = s.dumps(value)
# 
#     def list_fields(self):
#         s = QSerializer(base64=True)
#         d = s.loads(self.b64_query, raw=True)
#         return s.get_field_values_list(d)
# 
# Path: advanced_filters/form_helpers.py
# class CleanWhiteSpacesMixin:
#     """
#     This mixin, when added to any form subclass, adds a clean method which
#     strips repeating spaces in and around each string value of "clean_data".
#     """
#     def clean(self):
#         """
#         >>> import django.forms
#         >>> class MyForm(CleanWhiteSpacesMixin, django.forms.Form):
#         ...     some_field = django.forms.CharField()
#         >>>
#         >>> form = MyForm({'some_field': ' a   weird value  '})
#         >>> assert form.is_valid()
#         >>> assert form.cleaned_data == {'some_field': 'a weird value'}
#         """
#         cleaned_data = super().clean()
#         for k in self.cleaned_data:
#             if isinstance(self.cleaned_data[k], str):
#                 cleaned_data[k] = re.sub(extra_spaces_pattern, ' ',
#                                          self.cleaned_data[k] or '').strip()
#         return cleaned_data
# 
# class VaryingTypeCharField(forms.CharField):
#     """
#     This CharField subclass returns a regex OR patterns from a
#     comma separated list value.
#     """
#     _default_separator = ","
# 
#     def to_python(self, value):
#         """
#         Split a string value by separator (default to ",") into a
#         list; then, returns a regex pattern string that ORs the values
#         in the resulting list.
# 
#         >>> field = VaryingTypeCharField()
#         >>> assert field.to_python('') == ''
#         >>> assert field.to_python('test') == 'test'
#         >>> assert field.to_python('and,me') == '(and|me)'
#         >>> assert field.to_python('and,me;too') == '(and|me;too)'
#         """
#         res = super().to_python(value)
#         split_res = res.split(self._default_separator)
#         if not res or len(split_res) < 2:
#             return res.strip()
# 
#         # create a regex string out of the list of choices passed, i.e: (a|b)
#         res = r"({pattern})".format(pattern="|".join(
#             map(lambda x: x.strip(), split_res)))
#         return res


# Path: advanced_filters/forms.py
from datetime import datetime as dt
from pprint import pformat
from django import forms
from django.apps import apps
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.utils import get_fields_from_path
from django.core.exceptions import FieldDoesNotExist
from django.db.models import Q
from django.db.models.fields import DateField
from django.forms.formsets import formset_factory, BaseFormSet
from functools import reduce
from django.utils.text import capfirst
from django.utils.translation import gettext_lazy as _
from .models import AdvancedFilter
from .form_helpers import CleanWhiteSpacesMixin,  VaryingTypeCharField
import logging
import operator

            self.fields['field'].initial = self.FIELD_CHOICES[0]


class AdvancedFilterFormSet(BaseFormSet):
    """ """
    fields = ()
    extra_kwargs = {}

    def __init__(self, *args, **kwargs):
        self.model_fields = kwargs.pop('model_fields', {})
        super().__init__(*args, **kwargs)
        if self.forms:
            form = self.forms[0]
            self.fields = form.visible_fields()

    def get_form_kwargs(self, index):
        kwargs = super().get_form_kwargs(index)
        kwargs['model_fields'] = self.model_fields
        return kwargs


AFQFormSet = formset_factory(
    AdvancedFilterQueryForm, formset=AdvancedFilterFormSet,
    extra=1, can_delete=True)

AFQFormSetNoExtra = formset_factory(
    AdvancedFilterQueryForm, formset=AdvancedFilterFormSet,
    extra=0, can_delete=True)



class AdvancedFilterForm(CleanWhiteSpacesMixin, forms.ModelForm):