import datetime

from django.http import QueryDict
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework.permissions import AllowAny
from ticket.helper import send_image_to_server
from notification.models import (
    Notification,
    NotificationToken,
    NotificationType,
    Group
)
from panel.models import (
    PoultryRequest,
    CityOperatorCheckRequest,
    ProvinceCheckOperatorRequest,
    KillHouseRequest,
    FunctionExecutor
)
from notification.serializers import NotificationSerializer
from authentication.filterset import UserProfileFilterSet
from django_filters.rest_framework import DjangoFilterBackend
from authentication.models import UserProfile
from rest_framework.response import Response
from rest_framework import viewsets, status
from django.shortcuts import render
from .najva.send_notif_to_segments import (
    send_notification_to_all_segments,
    send_notification_to_specific_segment
)
from .najva.get_segments_detail import (
    get_segments
)
from authentication.views import (
    CLIENT_ID,
    CLIENT_SECRET,
    CACHE_TTL,
    ARVAN_User_Image_URL
)
import random
import string
import os

ARVAN_NOTIFICATION_GALLERY_URL = "https://profileimagedefault.s3.ir-thr-at1.arvanstorage.ir/"


class NajvaNotificationViewSet(viewsets.ModelViewSet):
    queryset = NotificationToken.objects.all()
    serializer_class = NotificationSerializer
    permission_classes = [AllowAny]
    filter_backends = [DjangoFilterBackend]
    filterset_class = UserProfileFilterSet
    filterset_fields = [
        'fullname',
        'mobile',
        'breeding_unique_id',
        'address__city',
        'address__province',
        'role__name',
    ]

    def list(self, request, *args, **kwargs):
        if "key" in request.GET:
            add_obj = Notification.objects.get(key__exact=request.GET["key"])
            serializer = self.serializer_class(add_obj)
            return Response(serializer.data, status=status.HTTP_200_OK)
        if "read_notif" in request.GET:
            add_obj = Notification.objects.filter(
                user_id=request.user.id, status="read"
            )
            query = [x for x in add_obj]
            serializer = self.serializer_class(query, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        if "unread_notif" in request.GET:
            add_obj = Notification.objects.filter(
                user_id=request.user.id, status="unread"
            )
            query = [x for x in add_obj]
            serializer = self.serializer_class(query, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        if "pending_notif" in request.GET:
            add_obj = Notification.objects.filter(
                user_id=request.user.id, status="pending"
            )
            query = [x for x in add_obj]
            serializer = self.serializer_class(query, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            queryset = Notification.objects.all()
            serializer = self.serializer_class(queryset, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):
        segments = []
        userprofile = UserProfile.objects.get(user=request.user)
        ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k=15))
        notification = Notification()
        if 'image' in request.data.keys():
            image = request.data['image']
            notification_image = send_image_to_server(image)
        if 'icon' in request.data.keys():
            icon = request.data['icon']
            notification_icon = send_image_to_server(icon)
        if 'request_type' in request.data.keys():
            if request.data['request_type'] == "token":
                if not NotificationToken.objects.filter(user=userprofile):
                    notification = NotificationToken()
                    notification.token = request.data['token']
                    notification.user = userprofile
                    notification.save()
                    return Response(status=status.HTTP_200_OK)
                else:
                    return Response({"msg": "user already has token"}, status=status.HTTP_403_FORBIDDEN)
        if 'value' in request.data.keys():
            if not request.data['value']:
                send_notification = send_notification_to_specific_segment(
                    # title=request.data['title'],
                    # body=request.data['body'],
                    # content=request.data['content'],
                    # icon=notification_icon,
                    # image=notification_image,
                    # segments_include=request.data['segments_include'],
                    # segments_exclude=request.data['segments_exclude'],
                    subscriber_tokens=['c22206d3-248a-4c81-b7c2-de2cfe5e5766']
                    # subscriber_tokens=['2cc244fc-1340-4942-bf19-2ba9f66f44e6']
                )
                return Response(send_notification)
                notification.notif_type = NotificationType.objects.get(name="alluser")
            else:
                for key in request.data['value']:
                    if UserProfile.objects.filter(key__exact=key):
                        notif_user = NotificationToken.objects.get(user__key__exact=key)
                        segments.append(notif_user.token)
                    if Group.objects.filter(name__exact=key):
                        for item in NotificationToken.objects.filter(user__role__name=key):
                            segments.append(item.token)
                send_notification = send_notification_to_specific_segment(
                    title=request.data['title'],
                    body=request.data['body'],
                    content=request.data['content'],
                    icon=notification_icon,
                    image=notification_image,
                    subscriber_tokens=segments
                )
                notification.notif_type = NotificationType.objects.get(name=request.data['request_type'])
        notification.title = request.data['title']
        notification.content = request.data['content']
        notification.icon = notification_icon
        notification.image = notification_image
        notification.save()
        if 'value' in request.data.keys():
            for key in request.data['value']:
                if UserProfile.objects.filter(key__exact=key):
                    notification.notif_user.add(UserProfile.objects.get(key__exact=key))
                elif Group.objects.filter(name__exact=key):
                    notification.notif_group.add(Group.objects.get(name__exact=key))
                    for item in UserProfile.objects.filter(role=Group.objects.get(name__exact=key)):
                        notification.notif_user.add(item)
        return Response(send_notification)
