from utils import serializer
from rest_framework import serializers

from .models import *

from apps.system.serializers import DictSerializer, UserListSerializer
from apps.project.models import Project
from apps.plan.models import Member
from apps.project.serializers import PlanSerializer
from apps.plan.serializers import MemberSerializer
class ProjectSerializerX(serializers.ModelSerializer):
    create_by_ = UserListSerializer(source='create_by', read_only=True)
    certapps = serializers.SerializerMethodField()
    plan_ = PlanSerializer(source='plan', read_only=True)
    members = serializers.SerializerMethodField()
    class Meta:
        model = Project
        fields = '__all__'
    
    def get_certapps(self, obj):
        certapps = []
        for i in obj.certapp_project.filter(is_deleted=False):
            certapps.append(i.cert_field.code +'(' +  i.cccpv_class.name +')')
        return certapps
    
    def get_members(self, obj):
        queryset = obj.certapp_project.all()
        members = Member.objects.filter(certapp__in=queryset, is_accepted=True, is_deleted=False).distinct('is_leader','user').order_by('-is_leader')
        serializer = MemberSerializer(members, many=True)
        return serializer.data
        

    @staticmethod
    def setup_eager_loading(queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.select_related('create_by', 'plan')
        queryset = queryset.prefetch_related('certapp_project',)
        return queryset

class CertappSerializerX(serializers.ModelSerializer):
    cert_field_ = DictSerializer(source='cert_field', read_only=True)
    cccpv_class_ = DictSerializer(source='cccpv_class' , read_only=True)
    cnas_scopes_ = DictSerializer(source='cnas_scopes', many=True , read_only=True)
    create_by_ = UserListSerializer(source='create_by', read_only=True)
    accept_by_ = UserListSerializer(source='accept_by', read_only=True)
    members = serializers.SerializerMethodField()
    class Meta:
        model = CertApp
        fields = '__all__'
    
    @staticmethod
    def setup_eager_loading(queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.select_related('cert_field', 'cccpv_class', 'create_by', 'accept_by')
        queryset = queryset.prefetch_related('cnas_scopes', 'member_certapp')
        return queryset
    
    def get_members(self, obj):
        members = Member.objects.filter(certapp=obj, is_accepted=True, is_deleted=False).order_by('-is_leader')
        serializer = MemberSerializer(members, many=True)
        return serializer.data