from django import forms
from .models import Sample
from core.widgets import CustomDateTimeWidget, NumberWithUnitWidget
from django.db.models import Q
from bags.models import Bag


# custom odour sample form to allow for easier cross field validation
class SampleForm(forms.ModelForm):
    class Meta:
        model = Sample
        exclude = []
        widgets = {
            'sampled_at': CustomDateTimeWidget(),
            'factor': NumberWithUnitWidget(suffix='')
        }

    def __init__(self, *args, **kwargs):
        super(SampleForm, self).__init__(*args, **kwargs)
        # restrict choices for pre dilution source, can't pre diluted from self
        self.fields['source_sample'].queryset = Sample.objects.all().exclude(pk=self.instance.pk)
        # restrict bag choice to the current bag and those which are active and empty
        if self.instance.pk is not None:  # update, keep current bag
            self.fields['contained_in'].queryset = \
                Bag.objects.filter((Q(is_active=True) & Q(sample__isnull=True)) | Q(sample__pk=self.instance.pk))
        else:  # create, the query for the update case would catch inactive but empty bags (comparing None to None)
            self.fields['contained_in'].queryset = \
                Bag.objects.filter((Q(is_active=True) & Q(sample__isnull=True)))

    # make sure to return something useful whatever path we take
    def save(self, commit=True):
        if self.instance.pk is not None and Sample.has_measurement(self.instance.pk):  # editing a sample with ex. meas
            old = Sample.objects.get(id=self.instance.pk)  # check if history affecting fields where changed
            if self.instance.cylinder != old.cylinder \
                    or self.instance.source_sample != old.source_sample \
                    or self.instance.factor != old.factor:
                retval = super(SampleForm, self).save(True)
                from panelists.qualification import update_panel_qualification
                update_panel_qualification()
                return retval
            else:
                return super(SampleForm, self).save(True)
        else:
            return super(SampleForm, self).save(True)