from .models import Sample
from core.views import ModelListViewBase, DetailedModelViewBase, SimpleCreateViewBase, SimpleUpdateViewBase
from .forms import SampleForm
from rest.serializers import OdourSamplesSerializer, ReferenceSamplesSerializer, AllSamplesSerializer
from users.access_checks import LoginRequiredMixin

# everyone is allowed to mess around in samples


class SampleListView(LoginRequiredMixin, ModelListViewBase):
    # set serializer anyway, although it may get overruled by the query string
    # but the activate mechanism uses the serializer to access the model class
    # while the querystring is not present at that stage (post vs get)
    serializer = AllSamplesSerializer
    sample_type = None

    def get_query(self):
        qs = Sample.objects.all().prefetch_related('cylinder', 'project', 'contained_in')
        if self.sample_type == 'reference':
            return qs.filter(cylinder__isnull=False)
        elif self.sample_type == 'odour':
            return qs.filter(cylinder__isnull=True)
        else:
            return qs

    def get(self, request, *args, **kwargs):
        self.sample_type = request.GET.get('type', None)
        if self.sample_type == 'reference':
            self.serializer = ReferenceSamplesSerializer
        elif self.sample_type == 'odour':
            self.serializer = OdourSamplesSerializer
        else:
            self.template_name = 'samples/samples_overview.html'
            self.serializer = AllSamplesSerializer

        return super(SampleListView, self).get(request, *args, **kwargs)


class SampleDetailView(LoginRequiredMixin, DetailedModelViewBase):
    model = Sample
    template_name = 'samples/sample_detail.html'

    def get_context_data(self, **kwargs):
        ctx = super(SampleDetailView, self).get_context_data(**kwargs)
        from rest.serializers import MeasurementSerializerWithVerboseMethod

        mser = MeasurementSerializerWithVerboseMethod(self.object.measurements.all(), many=True)
        ctx['measurements'] = mser.data

        # build dilution 'back log'
        ctx['dilution_back_log'] = self.object.get_dilution_back_log(list())
        ctx['dilution_forward_log'] = self.object.get_dilution_forward_log()
        return ctx


class SampleUpdateView(LoginRequiredMixin, SimpleUpdateViewBase):
    model = Sample
    form_class = SampleForm


class SampleCreateView(LoginRequiredMixin, SimpleCreateViewBase):
    model = Sample
    form_class = SampleForm

    def get_context_data(self, **kwargs):
        ctx = super(SampleCreateView, self).get_context_data(**kwargs)
        for_project = self.request.GET.get('project', None)
        if for_project is not None:
            ctx['form'].initial['project'] = for_project
        return ctx