from django.contrib.auth import get_user_model

from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from intranet.femida.src.actionlog.models import LogRecord, Snapshot
from intranet.femida.src.api.actionlog.serializers import LogRecordSerializer
from intranet.femida.src.api.core.pagination import CursorPagination
from intranet.femida.src.api.core.permissions import IsSuperuser
from intranet.femida.src.api.core.views import BaseView
from . import forms


User = get_user_model()


class LogMetaView(BaseView):

    permission_classes = [IsAuthenticated, IsSuperuser]

    def get(self, *args, **kwargs):
        action_names = LogRecord.objects.values_list('action_name', flat=True).distinct()
        return Response({
            'action_names': [{
                'name': name,
                'verbose_name': name,
            } for name in sorted(action_names)]
        })


class LogRecordPagination(CursorPagination):

    ordering = '-action_time'


class LogView(BaseView):

    model_class = LogRecord
    permission_classes = [IsAuthenticated, IsSuperuser]
    list_item_serializer_class = LogRecordSerializer
    pagination_class = LogRecordPagination

    def get(self, *args, **kwargs):
        return self.list(*args, **kwargs)

    def filter_queryset(self, queryset):
        filter_form = forms.ActionlogFilterForm(
            data=self.request.query_params.dict(),
            context={
                'user': self.request.user,
            },
        )
        self.validate(filter_form)
        params = filter_form.cleaned_data
        if params['user']:
            queryset = queryset.filter(user__username=params['user'])

        if params['obj_id'] and params['obj_str']:
            queryset = queryset.filter(
                id__in=Snapshot.objects.filter(
                    obj_id=params['obj_id'],
                    obj_str=params['obj_str'],
                ).values('log_record')
            )

        if params['action_name']:
            queryset = queryset.filter(action_name=params['action_name'])
        if params['action_time__gte']:
            queryset = queryset.filter(action_time__gte=params['action_time__gte'])
        if params['action_time__lte']:
            queryset = queryset.filter(action_time__lte=params['action_time__lte'])
        return queryset
