from django.views.generic import DetailView, TemplateView
from django.forms import ModelForm
from django.views.generic.edit import FormMixin
from django.utils.translation import ugettext_lazy as _

from .models import Panelist
from core.views import DetailedModelViewBase, SimpleUpdateViewBase, SimpleCreateViewBase, ModelListViewBase
from rest.serializers import PanelistsSerializerWeb
from core.widgets import CustomDateWidget
from .qualification import full_history, PanelistHistoryForm
from utils.view_utils import default_detail_crumb, list_breadcrumb
from users.access_checks import LoginRequiredMixin
from .qualification import panelist_qualification_values

class PanelistForm(ModelForm):
    class Meta:
        model = Panelist
        widgets = {'date_of_birth': CustomDateWidget()}
        exclude = []


class PanelistsListView(LoginRequiredMixin, ModelListViewBase):
    serializer = PanelistsSerializerWeb
    model = Panelist


class PanelistDetailView(LoginRequiredMixin, DetailedModelViewBase):
    model = Panelist
    template_name = 'panelists/panelist_detail.html'


class PanelistUpdateView(LoginRequiredMixin, SimpleUpdateViewBase):
    model = Panelist
    form_class = PanelistForm


class PanelistCreateView(LoginRequiredMixin, SimpleCreateViewBase):
    model = Panelist
    form_class = PanelistForm


# panelist reference gas history view
class PanelistHistoryView(LoginRequiredMixin, FormMixin, DetailView):
    form_class = PanelistHistoryForm
    model = Panelist
    template_name = 'panelists/panelist_history.html'

    def get_context_data(self, **kwargs):
        ctx = super(PanelistHistoryView, self).get_context_data(**kwargs)
        ctx['form'] = self.get_form(self.get_form_class())
        substance = self.request.GET.get('substance', 'B')
        ctx['form'].initial['substance'] = substance
        from referencegases.models import ReferenceGas

        ctx['current_substance'] = ReferenceGas.verbose_name_substance(substance)
        ctx['history_data'] = full_history(self.object.pk, substance)
        ctx['substance_key'] = substance
        return ctx

    def bread(self):
        base = [list_breadcrumb(Panelist.overview_url, Panelist)]
        base.append(default_detail_crumb(Panelist.detail_url, self.object))
        base.append(
            {
                'url': '#',
                'label': _('performance')
            }
        )
        return base


# displays a sortable table which groups panelists by their
# performance towards a selected reference material
class PanelPerformanceView(LoginRequiredMixin, FormMixin, TemplateView):
    template_name = 'panelists/panel_performance.html'
    form_class = PanelistHistoryForm  # reference type selection

    def bread(self):
        return [{'url': '#', 'label': _('panel performance')}]

    def get_context_data(self, **kwargs):
        ctx = super(PanelPerformanceView, self).get_context_data(**kwargs)
        ctx['form'] = self.get_form(self.get_form_class())
        substance = self.request.GET.get('substance', 'B')
        ctx['form'].initial['substance'] = substance

        panel = Panelist.objects.filter(is_active=True).values('pk', 'first_name', 'last_name')

        data = list()

        for panelist in panel:
            p = panelist
            sigmean = panelist_qualification_values(p['pk'])
            if sigmean is not None:
                data.append(p)
                data[-1]['s_ite_10'] = 10 ** sigmean['sigma']
                data[-1]['y_ite_10'] = 10 ** sigmean['mean']
                data[-1]['timestamp'] = sigmean['timestamp'].date()
        ctx['data'] = data
        return ctx


class PanelistHistoryPrintView(LoginRequiredMixin, DetailView):
    model = Panelist
    template_name = 'panelists/panel_perf_print.html'
    context_object_name = 'panelist'

    def get_context_data(self, **kwargs):
        ctx = super(PanelistHistoryPrintView, self).get_context_data(**kwargs)
        substance = self.request.GET.get('substance', 'B')
        timespan = self.request.GET.get('timespan', None)
        hist = full_history(self.object.pk, substance, timespan)
        ctx['history'] = hist
        from referencegases.models import ReferenceGas

        ctx['current_substance'] = ReferenceGas.verbose_name_substance(substance)
        return ctx


class LabHistoryView(LoginRequiredMixin, TemplateView):
    # template_name = 'panel_history/lab_history.html'

    def bread(self):
        return [{'url': '#',
                 'label': _('lab performance')}]

    def get_context_data(self, **kwargs):
        ctx = super(LabHistoryView, self).get_context_data(**kwargs)

        from .qualification import LABHIST_MU, LABHIST_AW_20, LABHIST_STUDENT_20
        from .qualification import full_lab_history

        glob = {'t_20': LABHIST_STUDENT_20,
                'Aw_20': LABHIST_AW_20,
                'MU': LABHIST_MU}

        ctx.update(glob)

        timespan = self.request.GET.get('timespan', None)

        history_data = full_lab_history(timespan)

        ctx['history_data'] = history_data
        return ctx