from django.shortcuts import render
from django.utils.safestring import mark_safe
import json

from rest_framework import viewsets as meviewsets
from app.applicationlayer.management.notification import serializers
from app.entities import models
from app.applicationlayer import paginators

from datetime import datetime

from rest_framework.response import Response
from rest_framework import status

from django.conf import settings
from app.applicationlayer.management.notification.utils_notif import (
                                            CustomPagination)
from rest_framework.exceptions import ValidationError
from django.shortcuts import render, redirect, get_object_or_404
from rest_framework.decorators import action
from app.applicationlayer.utils import (status_message_response)


class NotificationsViewset(meviewsets.ModelViewSet):

    lookup_field = 'account_no'
    queryset = models.Notification.objects.all()
    serializer_class = serializers.NotificationSerializer
    pagination_class = CustomPagination

    def list(self, request, *args, **kwargs):
        try:
            req = self.request
            account_no = req.query_params.get('account_no')
            app = req.query_params.get('app')
            
            if account_no:
                
                queryset = models.Notification.objects.filter(
                    account_no=account_no).order_by('-created')
                queryset = self.filter_queryset(queryset)
                unseen = models.Notification.objects.filter(
                    account_no=account_no, is_read=False).count()

                if app:

                    queryset = models.Notification.objects.filter(
                        account_no=account_no, app=app).order_by('-created')
                    queryset = self.filter_queryset(queryset)
                    unseen = models.Notification.objects.filter(
                        account_no=account_no, app=app, is_read=False).count()
                
            else:
                queryset = models.Notification.objects.all().order_by('-created')
                queryset = self.filter_queryset(queryset)
                unseen = models.Notification.objects.filter(
                    is_read=False).count()

            if not queryset:
                message = status_message_response(
                                200, 'success', 'No records found', []
                            )
                
                return Response(message)

            serializer = self.get_serializer(queryset, many=True)
            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                message = {
                    'unseen': unseen,
                    'code': 200,
                    'status': 'success',
                    'message': 'List of Notifications found',
                    'results': serializer.data
                }

                return self.get_paginated_response(message)
    
        except Exception as e:
            message = status_message_response(
                500, 'failed',
                'Request was not able to process' + str(e), [])
            return Response(message,
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # comment
    @action(methods=["PATCH"], detail=True)
    def seen(self, request, account_no=None, **kwargs):
        try:
            account_no = self.kwargs['account_no']
            
            models.Notification.objects.filter(account_no=account_no,
                                                id__in=request.data['ids']).update(
                                                is_read=True,
                                                modified=datetime.now())
            
            message = status_message_response(
                            200, 'success',
                            'Status successfully updated',
                            "None"
                        )
            
            return Response(message)

        except Exception as e:
            message = status_message_response(
                            500, 'failed',
                            'Request was not able to process' + str(e), []
                        )
            return Response(message,
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


    @action(methods=["PATCH"], detail=True)
    def seenall(self, request, account_no=None, **kwargs):
        try:
            account_no = self.kwargs['account_no']
            
            models.Notification.objects.filter(account_no=account_no).update(
                                                is_read=True,
                                                modified=datetime.now())
            
            message = status_message_response(
                            200, 'success',
                            'Status successfully updated',
                            "None"
                        )
            
            return Response(message)

        except Exception as e:
            message = status_message_response(
                            500, 'failed',
                            'Request was not able to process' + str(e), []
                        )
            return Response(message,
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


def index(request):
    return render(request, 'chat/index.html', {})


def room(request, room_name):
    return render(request, 'chat/room.html', {
        'room_name_json': mark_safe(json.dumps(room_name))
    })