import random

from rest_framework import viewsets
from oauth2_provider.contrib.rest_framework import (
    TokenHasReadWriteScope,
)
from .models import (
    Ticket,
    TicketContent,
    Answer,
    Question,
    SupportUnit,
    Group,
    SystemUserProfile
)
from .serializers import (
    TicketSerializer,
    TicketContentSerializer,
    TicketAnswerSerializer,
    TicketQuestionSerializer,
    SupportUnitSerializer
)
from rest_framework.response import Response
from .helper import upload_listed_image
from rest_framework import status
from datetime import datetime


class CustomerTicketViewSet(viewsets.ModelViewSet):
    queryset = Ticket.objects.all()
    serializer_class = TicketSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        # get user object
        user = SystemUserProfile.objects.get(user=request.user)

        # different style of ticket information
        if 'pending' in request.GET:
            ticket = self.queryset.filter(customer=user, state='pending')
            serializer = self.serializer_class(ticket, many=True)
        elif 'responded' in request.GET:
            ticket = self.queryset.filter(customer=user, state='responded')
            serializer = self.serializer_class(ticket, many=True)
        elif 'closed' in request.GET:
            ticket = self.queryset.filter(customer=user, state='closed')
            serializer = self.serializer_class(ticket, many=True)
        elif 'all' in request.GET:
            ticket = self.queryset.filter(customer=user)
            serializer = self.serializer_class(ticket, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def retrieve(self, request, *args, **kwargs):
        ticket = self.queryset.get(key=request.data['key'])
        serializer = self.serializer_class(ticket)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):

        if 'ticket_key' in request.data.keys():
            ticket_key = request.data['ticket_key']
            request.data.pop('ticket_key')
        else:
            ticket_key = None

        # get group unit information
        group = Group.objects.get(
            name__exact=request.data['support_unit']
        )
        request.data.pop('support_unit')  # pop this block from body data

        # get support unit object information
        support_unit = SupportUnit.objects.get(
            unit=group
        )

        # ticket number
        ticket_id = random.randint(1000000, 9999999)

        # process list of images
        req = upload_listed_image(req=request, field='image')

        # create ticket content
        content_serializer = TicketContentSerializer(data=req.data)
        if content_serializer.is_valid():
            content_obj = content_serializer.create(validated_data=req.data)

        # create question from customer
        question = Question(
            questioner=SystemUserProfile.objects.get(user=request.user),
            content=content_obj
        )
        question.save()

        if ticket_key is not None:
            ticket = Ticket.objects.get(key=ticket_key)
            ticket.question.add(question)
            ticket.state = 'pending'
            ticket.save()
        else:
            # create final ticket
            ticket = Ticket(
                customer=SystemUserProfile.objects.get(user=request.user),
                support_unit=support_unit,
                state='pending',
                ticket_id=ticket_id
            )
            ticket.save()
            ticket.question.add(question)

        serializer = self.serializer_class(ticket)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        ticket = self.queryset.get(key=request.data['ticket_key'])  # contains ticket object
        request.data.pop('ticket_key')

        # send ticket object to serializer for update
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            ticket_updated = serializer.update(validated_data=request.data, instance=ticket)
            serializer = self.serializer_class(ticket_updated)
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors)

    def destroy(self, request, *args, **kwargs):
        pass
