from rest_framework import generics, filters
from .models import Task, TaskManager
from .serializers import TaskSerializer, TaskManagerSerializer
from rest_framework import viewsets, mixins

# List & Create tasks
class TaskListCreateUpdateView(generics.ListCreateAPIView, generics.UpdateAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    filter_backends = [filters.OrderingFilter, filters.SearchFilter]
    ordering_fields = ["created_at", "due_date", "priority"]
    search_fields = ["title", "description"]

# Retrieve & Update a single task
class TaskRetrieveUpdateView(generics.RetrieveUpdateAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    lookup_field = "id"


# @api_view(["GET"])
# def tasks_by_profile(request, profile_id):
  
#     tasks = Task.objects.filter(assignee=profile_id)
#     serializer = TaskSerializer(tasks, many=True)
#     return Response(serializer.data)


class TasksByProfileView(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = TaskSerializer

    def get_queryset(self):
        profile_id = self.kwargs.get('uuid')
        return Task.objects.filter(assignee__id=profile_id).select_related('assignee').order_by('-created_at')

    
class TaskManagerListCreateView(generics.ListCreateAPIView):
    queryset = TaskManager.objects.all().select_related('client_name', 'designed_by', 'allotted_by')
    serializer_class = TaskManagerSerializer
    filter_backends = [filters.OrderingFilter, filters.SearchFilter]
    ordering_fields = ["created_at", "date", "job_order_no"]
    search_fields = ["job_order_no", "activities", "work_details"]

class TaskManagerRetrieveUpdateView(generics.RetrieveUpdateAPIView):
    queryset = TaskManager.objects.all().select_related('client_name', 'designed_by', 'allotted_by')
    serializer_class = TaskManagerSerializer
    lookup_field = "id"

class TaskManagerByProfileView(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = TaskManagerSerializer

    def get_queryset(self):
        profile_id = self.kwargs.get('uuid')
        return TaskManager.objects.filter(designed_by__id=profile_id).select_related('allotted_by').order_by('-created_at')
    
    # def get_serializer_context(self):
    #     context = super().get_serializer_context()
    #     context['allotted_by'] = self.request.user
    #     return context  