from apps.notification.pos.api.v1.serializers import NotificationSerializer
from apps.pos_device.mixins.pos_device_mixin import POSDeviceMixin
from apps.core.mixins.soft_delete_mixin import SoftDeleteMixin
from apps.core.mixins.search_mixin import DynamicSearchMixin
from apps.notification.models import Notification
from rest_framework.permissions import AllowAny
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework import status
from django.db import transaction
from django.db.models import Q


class NotificationViewSet(SoftDeleteMixin, POSDeviceMixin, DynamicSearchMixin, viewsets.ModelViewSet):
    queryset = Notification.objects.all().select_related('organization')
    serializer_class = NotificationSerializer
    permission_classes = [AllowAny]

    def list(self, request, *args, **kwargs):
        """ show all notifications of device """

        organization = self.get_device_organization()
        device = self.get_pos_device()

        show_type = self.request.query_params.get('show')

        if show_type == 'undelivered':
            queryset = self.queryset.filter(
                Q(delivering_type='general') | Q(delivering_type='private'),
                device=device,
                organization=organization,
                delivered=False,
                is_read=False,
            )
        elif show_type == 'unread':
            queryset = self.queryset.filter(
                Q(delivering_type='general') | Q(delivering_type='private'),
                device=device,
                organization=organization,
                delivered=True,
                is_read=False
            )
        else:
            queryset = self.queryset

        # paginate & response
        page = self.paginate_queryset(queryset)

        # set notifications delivered status to true
        queryset.update(delivered=True)

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

    @action(
        methods=['put'],
        detail=True,
        url_path='read_notification',
        url_name='read_notification',
        name='read_notification',
    )
    @transaction.atomic
    def read_notification(self, request, pk=None):
        """ read notification by pos organization """

        query = self.get_object()

        query.is_read = True
        query.save()

        return Response(status=status.HTTP_200_OK)
