from app.entities import models
from rest_framework import serializers
from django.db.models import Q
from drf_writable_nested import WritableNestedModelSerializer
from app.applicationlayer.utils import model_to_dict


class ChangeRequestFormApproversSerializer(
    serializers.ModelSerializer
):
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        try:
            ret['company'] = model_to_dict(instance.user.department.company)
            ret['department'] = model_to_dict(instance.user.department)
            user_object = {
                "id": instance.user.id,
                "name": instance.user.name,
                "username": instance.user.username,
                "code": instance.user.code,
                "email": instance.user.email,
                "contact_no": instance.user.contact_no
            }
            ret['user'] = user_object
            return ret
        
        except Exception as e:
            ret['user'] = "none"
            ret['department'] = "none"
            ret['company'] = "none"
            return ret

    class Meta:
        model = models.ChangeRequestFormApprovers
        fields = '__all__'
        read_only_fields = ['created', 'code']


class ChangeRequestFormStakeHoldersSerializer(
    serializers.ModelSerializer
):
    class Meta:
        model = models.ChangeRequestFormStakeHolders
        fields = '__all__'
        read_only_fields = ['created', 'code']


class ChangeRequestFormAttachmentsSerializer(
    serializers.ModelSerializer
):
    class Meta:
        model = models.ChangeRequestFormAttachments
        fields = '__all__'
        read_only_fields = ['created', 'code']


class ChangeRequestFormDetailsSerializer(
    serializers.ModelSerializer
):
    class Meta:
        model = models.ChangeRequestFormDetails
        fields = '__all__'
        read_only_fields = ['created', 'code']


class ChangeRequestFormHeaderSerializer(
    serializers.ModelSerializer
):
    frm_approvers = ChangeRequestFormApproversSerializer(
        many=True, read_only=True)
    frm_stakes = ChangeRequestFormStakeHoldersSerializer(
        many=True, read_only=True)
    frm_attachments = ChangeRequestFormAttachmentsSerializer(
        many=True, read_only=True)
    frm_details = ChangeRequestFormDetailsSerializer(
        many=True, read_only=True)
    
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        try:
            user = self.context['request'].user
            
            id_number = user.code
            
            current_level = models.ChangeRequestFormApprovers.objects.filter(
                Q(form_code=ret['form_code']) &
                (Q(action='') | Q(action=None))
            ).order_by('level')
            
            if current_level[0].user.code == id_number:
                if instance.status.lower() == 'rejected':
                    approver = 'No'
                elif instance.status.lower() == 'cancelled':
                    approver = 'No'
                elif instance.status.lower() == 'completed & accepted':
                    approver = 'No'
                else:
                    approver = 'Yes'
            else:
                approver = 'No'
            ret['action'] = approver
            ret['company'] = instance.requested_to_company.name
            ret['department'] = instance.requested_to_department.name
            ret['requested_by'] = instance.requested_by_user.name
            
            return ret
        except Exception as e:
            ret['action'] = "No"
            ret['company'] = "None"
            ret['department'] = "None"
            ret['requested_by'] = "None"

            return ret

    class Meta:
        model = models.ChangeRequestFormHeader
        # fields = '__all__'
        fields = ('form_code', 'requested_to_template_name', 'requested_to_objective',
                  'requested_to_target_date', 'requested_to_priority',
                  'description', 'created', 'cancel_date', 'status',
                  'company_desc', 'department_desc', 'requested_desc',
                  'requested_to_template_id', 'requested_to_company',
                  'requested_to_department', 'requested_to_user',
                  'requested_by_user', 'requested_by_department',
                  'template_no', 'frm_approvers', 'frm_stakes',
                  'frm_attachments', 'frm_details')

        read_only_fields = ['created', 'form_code']


class ChangeRequestFormHeaderSerializerList(
    serializers.ModelSerializer
):
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        try:
            user = self.context['request'].user
            
            id_number = user.code
            
            current_level = models.ChangeRequestFormApprovers.objects.filter(
                Q(form_code=ret['form_code']) &
                (Q(action='') | Q(action=None))
            ).order_by('level')
            
            if current_level[0].user.code == id_number:
                if instance.status.lower() == 'rejected':
                    approver = 'No'
                elif instance.status.lower() == 'cancelled':
                    approver = 'No'
                elif instance.status.lower() == 'completed & accepted':
                    approver = 'No'
                else:
                    approver = 'Yes'
            else:
                approver = 'No'
            ret['action'] = approver
            ret['company'] = instance.requested_to_company.name
            ret['department'] = instance.requested_to_department.name
            ret['requested_by'] = instance.requested_by_user.name
            
            return ret
        except Exception as e:
            ret['action'] = "No"
            ret['company'] = "None"
            ret['department'] = "None"
            ret['requested_by'] = "None"

            return ret

    class Meta:
        model = models.ChangeRequestFormHeader
        fields = '__all__'
        read_only_fields = ['created', 'form_code']