from rest_framework.settings import api_settings
from rest_framework import generics, permissions
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope
from . import serializers
from . import models
from django.contrib.auth.models import User
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.response import Response
from . import executor
from sales.models import Sale
from datetime import datetime, timedelta
from django.http import HttpResponse
from . import exports
from . import models
from core.paginators import CustomPagination, MyPaginationMixin
from core import logging
logger = logging.getLogger(__name__)


class TaskReportExportView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        agent = request.user.profile.agent
        data = models.Task.objects.all()
        export_id = datetime.now().strftime("%Y%m%d%H%M%S")
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = f'attachment; filename="{export_id}_Requests.xlsx"'
        xlsx_data = exports.export_requests(request, data)
        response.write(xlsx_data)
        return response


class TaskListView(APIView, MyPaginationMixin):
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
    serializer_class = serializers.TaskSerializer

    def post(self, request):
        agent = request.user.profile.agent
        data = request.data
        logger.debug(data)
        f = data
        qs = models.Task.objects.filter(**f)
        data = serializers.TaskSerializer(qs, many=True).data
        page = self.paginate_queryset(qs)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)
        return []
        # return Response({'result': 0, 'message': 'Fetched tasks successfully', 'data': data})


class ManageTaskMakerChecker(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        if 'pending' in request.GET and request.GET['pending']:
            res = models.Task.objects.filter(status=models.STATUS_INITIATED)
        else:
            res = models.Task.objects.all()
        return Response({'result': 0, 'message': 'Fetched tasks successfully', 'data': serializers.TaskSerializer(res, many=True).data, 'count': res.count()})

    def post(self, request):
        data = request.data
        data['maker'] = request.user
        sale = Sale.objects.get(pk=data['reference'])
        data['transaction_date'] = sale.transaction_date
        data['customer_name'] = sale.customer_name
        data['delivery_note'] = sale.delivery_note

        task = models.Task.objects.create(**data)
        if task.task_type.name == 'Sales Documents Delete':
            Sale.objects.filter(pk=task.reference).update(task=task)
        return Response({'result': 0, 'message': f'Successfully created task approval request with id: {task.id}'})

    def put(self, request, task_id):
        task = models.Task.objects.get(pk=task_id)
        status = request.data['status']
        result = None
        # if (statusm == models.STATUS_APPROVED and not task.task_type.reverse) or (status == models.STATUS_REJECTED and task.task_type.reverse):
        #     func = getattr(executor, task.task_type.executor)
        #     result = func(task)
        #     logger.debug(result)
        if (status == models.STATUS_APPROVED or status == models.STATUS_REJECTED):
            func = getattr(executor, task.task_type.executor)
            result = func(task, status=status)
            logger.debug(result)
            task.checker_comment = request.data['checker_comment']
            task.checker = request.user
            task.status = status
            task.result = result
            task.save()

            return Response({'result': 0, 'message': f'Successfully updated task approval request with id: {task.id}'})

        return Response({'result': -1, 'message': f'Approval execution failed, seems not valid status : {task.id} => {status}'})


class TaskTypeView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        name = request.data['name']
        tType = models.TaskType.objects.filter(name=name).first()
        return Response({'result': 0, 'message': f'Successfully fetched task type by name', 'data': serializers.TaskTypeSerializer(tType).data})
