from rest_framework import status, viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.plans.models import Plan
from .models import LeveeWorkSession
from .serializers import LeveeWorkSessionSerializer, LeveeWorkSessionWriteSerializer


class LeveeWorkSessionViewSet(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = LeveeWorkSession.objects.prefetch_related(
            'items',
            'items__field',
            'items__plan',
        ).select_related('work_record')
        year = self.request.query_params.get('year')
        if year:
            queryset = queryset.filter(year=year)
        return queryset

    def get_serializer_class(self):
        if self.action in ['create', 'update', 'partial_update']:
            return LeveeWorkSessionWriteSerializer
        return LeveeWorkSessionSerializer


class LeveeWorkCandidatesView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        year = request.query_params.get('year')
        if not year:
            return Response(
                {'detail': 'year が必要です。'},
                status=status.HTTP_400_BAD_REQUEST,
            )

        try:
            year = int(year)
        except (TypeError, ValueError):
            return Response(
                {'detail': 'year は数値で指定してください。'},
                status=status.HTTP_400_BAD_REQUEST,
            )

        plans = (
            Plan.objects.select_related('field', 'crop', 'variety')
            .filter(year=year, crop__name='水稲')
            .order_by('field__display_order', 'field__id')
        )

        data = [
            {
                'field_id': plan.field_id,
                'field_name': plan.field.name,
                'field_area_tan': str(plan.field.area_tan),
                'group_name': plan.field.group_name,
                'plan_id': plan.id,
                'crop_name': plan.crop.name,
                'variety_name': plan.variety.name if plan.variety else '',
                'selected': True,
            }
            for plan in plans
        ]
        return Response(data)

