from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from authentication.message.serializers import UserMessageSerializer
from panel.models import CheckState, OperatorLastTimeEnter
from authentication.sahandsms.sms import sms_reminder
from authentication.models import (
    UserMessage,
    UserProfile,
    SendingMessageMethod,
    UserMessageType, SystemUserProfile
)
from django.contrib.auth.models import Group
from rest_framework.response import Response
from notification.models import (
    NotificationToken,
    NotificationType,
    Notification
)
from notification.najva import (
    get_segments_detail,
    send_notif_to_segments
)
from rest_framework import viewsets
from rest_framework import status
import random
import string
import os

from ticket.helper import send_image_to_server

# آدرس پایه ذخیره عکس مربوط به سیستم پیام کاربر در استوریج آروان
ARVAN_user_message_URL = 'https://profileimagedefault.s3.ir-thr-at1.arvanstorage.ir/'


# ویو ست کلی برای سیستم پیام کاربر که شامل ساخت و ویرایش و حذف می باشد
# برای ساخت چند حالت دارد که یا برای یک شخص ارسال میشه یا جند شخص یا یک نقش خاص
class UserMessageViewSet(viewsets.ModelViewSet):
    queryset = UserMessage.objects.all()
    serializer_class = UserMessageSerializer
    permission_classes = [TokenHasReadWriteScope]

    def create(self, request, *args, **kwargs):
        try:
            images = request.data['image']
            request.data.pop('image')
        except:
            images = None

        try:
            roles = request.data['roles']
            request.data.pop('roles')
        except:
            roles = None

        try:
            users = request.data['users']
            request.data.pop('users')
        except:
            users = None

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            user_message = serializer.create(validated_data=request.data)
            user_message.sender = SystemUserProfile.objects.get(user=request.user)
            if roles == None:
                pass
            else:
                for role in roles:
                    rol = Group.objects.get(name=role)
                    user_message.roles.add(rol)
            if users == None and roles == None:
                for user in SystemUserProfile.objects.all():
                    user_message.users.add(user)
            elif users == None:
                user_list = []
                for rol in roles:
                    persons = SystemUserProfile.objects.filter(role__name=rol)
                    for user in persons:
                        user_list.append(user.key)
                for user in user_list:
                    user = SystemUserProfile.objects.get(key__exact=user)
                    user_message.users.add(user)
            else:
                for user in users:
                    user = SystemUserProfile.objects.get(key__exact=user)
                    user_message.users.add(user)
            if images == None:
                pass
            else:
                pic = []
                for image in images:
                    pic.append(send_image_to_server(image))
                user_message.image = pic
            user_message.save()
            serializer = self.serializer_class(user_message)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def list(self, request, *args, **kwargs):
        if 'sender' in request.GET:
            queryset = UserMessage.objects.filter(
                sender=SystemUserProfile.objects.get(user=request.user)
            )
        if 'receiver' in request.GET:
            user_id = SystemUserProfile.objects.get(user_id__exact=request.user.id)
            queryset = UserMessage.objects.filter(users=user_id)

        serializer = UserMessageSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        user = SystemUserProfile.objects.get(user_id=request.user.id)
        key = request.data['key']
        queryset = UserMessage.objects.get(key__exact=key)
        queryset.users.remove(user)
        queryset.save()
        return Response(status=status.HTTP_200_OK)


class SendingMessageMethodViewSet(viewsets.ModelViewSet):
    queryset = SendingMessageMethod.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = UserMessageViewSet

    def create(self, request, *args, **kwargs):
        if not SendingMessageMethod.objects.filter(level=request.data['level']):
            SendingMessageMethod(
                level=request.data['level'],
                methods='/'.join(request.data['methods'])
            ).save()
            return Response({'msg': 'Done'}, status=status.HTTP_200_OK)
        return Response({'msg': 'Method Exist'}, status=status.HTTP_403_FORBIDDEN)

    def update(self, request, *args, **kwargs):
        method = SendingMessageMethod.objects.get(key__exact=request.data['key'])
        method.level = request.data['level']
        method.methods = '/'.join(request.data['methods'])
        method.save()
        return Response({'msg': 'Done'}, status=status.HTTP_200_OK)


class SendSMSViewSet(viewsets.ModelViewSet):
    queryset = UserMessage.objects.all()
    serializer_class = UserMessageSerializer
    permission_classes = [TokenHasReadWriteScope]

    def create(self, request, *args, **kwargs):
        segments = []
        usermessage = UserMessage()
        usermessage.message_level = "sms"
        if 'value' in request.data.keys():
            for key in request.data['value']:
                if UserProfile.objects.filter(key__exact=key):
                    segments.append(UserProfile.objects.get(key__exact=key))
                if Group.objects.filter(name__exact=key):
                    for item in UserProfile.objects.filter(role__name__exact=key):
                        segments.append(item)
            usermessage.message_type = UserMessageType.objects.get(name__exact=request.data['request_type'])
            for i in segments:
                sms_reminder(
                    receptor=i.mobile,
                    title=request.data['heading'],
                    content=request.data['message'],
                    link_text=request.data['link_text'],
                    link=request.data['link'],
                    time=request.data['time']
                )
            if not request.data['value']:
                for item in UserProfile.objects.filter(role__name__exact="Poultry"):
                    sms_reminder(
                        receptor=item.mobile,
                        title=request.data['heading'],
                        content=request.data['message'],
                        link_text=request.data['link_text'],
                        link=request.data['link'],
                        time=request.data['time']
                    )
            usermessage.heading = request.data['heading']
            usermessage.message = request.data['message']
            usermessage.link_text = request.data['link_text']
            usermessage.link = request.data['link']
            usermessage.time = request.data['time']
            usermessage.save()
            if 'value' in request.data.keys():
                for key in request.data['value']:
                    if UserProfile.objects.filter(key__exact=key):
                        usermessage.users.add(UserProfile.objects.get(key__exact=key))
                    if Group.objects.filter(name__exact=key):
                        usermessage.roles.add(Group.objects.get(name__exact=key))
        request.data.pop('value')
        request.data.pop('request_type')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.create(validated_data=request.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)
