from django.shortcuts import render
from rest_framework import status
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from authentication.auth import verify_token

from .models import Notifications
from .serializer import NotificationSerializer


@csrf_exempt
def notifications(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message': "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED}, safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        if request.method == 'POST':
            request_data = json.loads(request.body)
            notification = Notifications()
            notification.title = request_data['title']
            notification.body = request_data['body']
            notification.send_to = int(request_data['send_to'])
            notification.save()
            return JsonResponse({'message': "Notification Send succesfully.", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else:
            notifications = Notifications.objects.all()
            serializer = NotificationSerializer(notifications, many=True)
            return JsonResponse({'notifications': serializer.data, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)


@csrf_exempt
def deleteNotification(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message':"User not login.", 'status':status.HTTP_401_UNAUTHORIZED}, safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        try:
            request_data = json.loads(request.body)        
            Notifications.objects.get(id = request_data['id']).delete()
            return JsonResponse({'message': "Notification deleted Successfully", 'status': status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        except Notifications.DoesNotExist:
            return JsonResponse({'message': "Notification doesn't exists. Invalid Notification id", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
