from django import forms

from .models import ReferenceGas
from core.views import DetailedModelViewBase, SimpleCreateViewBase, ModelListViewBase
from core.views import SimpleUpdateViewBase
from core.widgets import CustomDateWidget, NumberWithUnitWidget
from rest.serializers import ReferenceGasesSerializer
from users.access_checks import LoginRequiredMixin
from users.models import HEAD_OF_LAB_ID


class ReferenceGasForm(forms.ModelForm):
    class Meta:
        model = ReferenceGas
        widgets = {"in_service_since": CustomDateWidget(),
                   "expires_at": CustomDateWidget(),
                   "concentration": NumberWithUnitWidget(suffix='ppm')}
        exclude = []

    def save(self, commit=True):
        if self.instance.pk is not None:  # editing
            old = ReferenceGas.objects.get(id=self.instance.pk)  # check if history affecting fields where changed
            if self.instance.substance != old.substance \
                    or self.instance.concentration != old.concentration:
                retval = super(ReferenceGasForm, self).save(True)
                from panelists.qualification import update_panel_qualification
                update_panel_qualification()
                return retval
            else:
                return super(ReferenceGasForm, self).save(True)
        else:
            return super(ReferenceGasForm, self).save(True)

class ReferenceGasesListView(LoginRequiredMixin, ModelListViewBase):
    serializer = ReferenceGasesSerializer
    require_group = HEAD_OF_LAB_ID


class ReferenceGasDetailView(LoginRequiredMixin, DetailedModelViewBase):
    model = ReferenceGas
    require_group = HEAD_OF_LAB_ID


class ReferenceGasUpdateView(LoginRequiredMixin, SimpleUpdateViewBase):
    model = ReferenceGas
    form_class = ReferenceGasForm
    require_group = HEAD_OF_LAB_ID


class ReferenceGasCreateView(LoginRequiredMixin, SimpleCreateViewBase):
    model = ReferenceGas
    form_class = ReferenceGasForm
    require_group = HEAD_OF_LAB_ID
