from .models import HistoryEntry
from rest.serializers import HistoryEntrySerializer
from django.views.generic import TemplateView
from users.access_checks import LoginRequiredMixin
from django.utils.translation import force_text


class HistoryDetailView(LoginRequiredMixin, TemplateView):
    template_name = 'history_detail.html'
    fields = HistoryEntrySerializer.Meta.fields

    @staticmethod
    def datatables_translation():
        from core.views import ModelListViewBase

        return ModelListViewBase.datatables_translation()

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

        # forward object and content type pk to rest view
        ctx['oid'] = self.request.GET.get('oid', None)
        ctx['ct'] = self.request.GET.get('ct', None)

        field_names = list()
        verbose_names = list()
        for fn in self.fields:
            field_names.append(fn)
            verbose_names.append(HistoryEntry._meta.get_field_by_name(fn)[0].verbose_name)
        ctx['field_names'] = field_names
        ctx['verbose_names'] = verbose_names
        qset = HistoryEntry.objects.filter(content_type=ctx['ct']).filter(object_id=ctx['oid'])
        ser = HistoryEntrySerializer(qset, many=True)
        ctx['object_list'] = ser.data
        obj = ctx['object'] = qset.first().entity
        # spice up the list with the verbose names for each field
        # in addtion, check if the field is a choice field and lookup the
        # verbose titles for the choices
        for entry in ctx['object_list']:
            try:
                maybeField = obj._meta.get_field(entry['field_name'])
                entry['field_name'] = maybeField.verbose_name.title()

                # wrap choice field lookup into a separate try catch, when it fails
                # we might still have the verbose field names around
                try:
                    if hasattr(maybeField, 'choices'):
                        choice_list = maybeField.choices
                        # fuck you runtime!
                        if len(choice_list) > 0:
                            ov = entry['old_value']
                            nv = entry['new_value']
                            ov_verbose = [c[1] for c in choice_list if c[0] == ov][0]
                            nv_verbose = [c[1] for c in choice_list if c[0] == nv][0]
                            entry['old_value'] = force_text(ov_verbose)
                            entry['new_value'] = force_text(nv_verbose)
                except:
                    pass
            except:
                pass

        return ctx


