from core.views import SimpleCreateViewBase, SimpleUpdateViewBase, DetailedModelViewBase, ModelListViewBase
from .models import Olfactometer, Calibration
from .forms import CalibrationUpdateCreateForm
from django.core.urlresolvers import reverse_lazy
from rest.serializers import OlfactometersSerializer, CalibrationsSerializer
from users.access_checks import LoginRequiredMixin

from users.models import HEAD_OF_LAB_ID

class OlfactometersListView(LoginRequiredMixin, ModelListViewBase):
    serializer = OlfactometersSerializer

    require_group = HEAD_OF_LAB_ID

    additional_buttons = [
        {'url': reverse_lazy(Calibration.overview_url),
         'label': Calibration._meta.verbose_name_plural, 'icon': 'icon-ruler'}
    ]


class OlfactometerDetailView(LoginRequiredMixin, DetailedModelViewBase):
    model = Olfactometer

    require_group = HEAD_OF_LAB_ID


class OlfactometerCreateView(LoginRequiredMixin, SimpleCreateViewBase):
    model = Olfactometer

    require_group = HEAD_OF_LAB_ID


class OlfactometerUpdateView(LoginRequiredMixin, SimpleUpdateViewBase):
    model = Olfactometer

    require_group = HEAD_OF_LAB_ID


class CalibrationsListView(LoginRequiredMixin, ModelListViewBase):
    serializer = CalibrationsSerializer

    require_group = HEAD_OF_LAB_ID


class CalibrationDetailView(LoginRequiredMixin, DetailedModelViewBase):
    model = Calibration
    skip_fields = ['json_data']
    template_name = 'devices/calibration_set_detail.html'

    require_group = HEAD_OF_LAB_ID

    def get_context_data(self, **kwargs):
        ctx = super(CalibrationDetailView, self).get_context_data(**kwargs)
        if self.object.json_data:
            from json import loads

            calib_data = (self.object.json_data.replace("'", "\""))
            ctx['calib_set'] = loads(calib_data)
        return ctx


class CalibrationUpdateView(LoginRequiredMixin, SimpleUpdateViewBase):
    model = Calibration
    form_class = CalibrationUpdateCreateForm

    require_group = HEAD_OF_LAB_ID


class CalibrationCreateView(LoginRequiredMixin, SimpleCreateViewBase):
    model = Calibration
    form_class = CalibrationUpdateCreateForm

    require_group = HEAD_OF_LAB_ID

