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 OperatorTicketViewSet(viewsets.ModelViewSet):
    queryset = Ticket.objects.all()
    serializer_class = TicketSerializer
    permission_classes = [TokenHasReadWriteScope]

    def ticket_by_flag(self, request, state):
        ticket_list = []
        roles = SystemUserProfile.objects.get(user=request.user).role.all()
        if state is not None:
            ticket = self.queryset.filter(state=state)
        else:
            ticket = self.queryset.all()
        for item in ticket:
            for role in roles:
                if item.support_unit.unit == role:
                    ticket_list.append(item)
        return ticket_list

    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_list = self.ticket_by_flag(request=request, state='pending')
            serializer = self.serializer_class(ticket_list, many=True)
        elif 'responded' in request.GET:
            ticket = self.queryset.filter(operator=user, state='responded')
            serializer = self.serializer_class(ticket, many=True)
        elif 'closed' in request.GET:
            ticket = self.queryset.filter(operator=user, state='closed')
            serializer = self.serializer_class(ticket, many=True)
        elif 'all' in request.GET:
            ticket_list = self.ticket_by_flag(request=request, state=None)
            serializer = self.serializer_class(ticket_list, 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):
        ticket = self.queryset.get(key=request.data['ticket_key'])  # contains ticket object
        request.data.pop('ticket_key')

        # get question object
        # question = Question.objects.get(key=request.data['question_key'])
        # request.data.pop('question_key')
        question = ticket.question.all().last()

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

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

        # create responder object information
        answer = Answer(
            responder=SystemUserProfile.objects.get(user=request.user),
            content=content_obj,
            question=question
        )
        answer.save()

        # set respond for ticket questioner
        ticket.operator = SystemUserProfile.objects.get(user=request.user)
        ticket.state = 'responded'
        ticket.save()
        ticket.respond.add(answer)

        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
