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

from app.applicationlayer.cms.form.approver.serializers import ChangeRequestFormApproversSerializer
from app.applicationlayer.cms.form.stakeholder.serializers import ChangeRequestFormStakeHoldersSerializer
from app.applicationlayer.cms.form.details.serializers import ChangeRequestFormDetailsSerializer
from app.applicationlayer.cms.form.attachment.serializers import ChangeRequestFormAttachmentsSerializer


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(is_action=True) &
                Q(user=id_number)
            ).order_by('level')
            
            if current_level.count() > 0: # and 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_required'] = approver
            
            requested_to_user = {
                "id": instance.requested_to_user.id,
                "name": instance.requested_to_user.name,
                "username": instance.requested_to_user.username,
                "code": instance.requested_to_user.code,
                "email": instance.requested_to_user.email,
                "contact_no": instance.requested_to_user.contact_no
            }

            requested_by_user = {
                "id": instance.requested_by_user.id,
                "name": instance.requested_by_user.name,
                "username": instance.requested_by_user.username,
                "code": instance.requested_by_user.code,
                "email": instance.requested_by_user.email,
                "contact_no": instance.requested_by_user.contact_no
            }

            # ret['requested_to_company'] = model_to_dict(instance.requested_to_company)
            ret['requested_to_company'] = {
                "id": instance.requested_to_company.id,
                "code": instance.requested_to_company.code,
                "name": instance.requested_to_company.name
            }
            # ret['requested_to_department'] = model_to_dict(instance.requested_to_department)
            ret['requested_to_department'] = {
                "id": instance.requested_to_department.id,
                "code": instance.requested_to_department.code,
                "name": instance.requested_to_department.name
            }
            ret['requested_to_user'] = requested_to_user
            ret['requested_by_user'] = requested_by_user
            ret['requested_by_department'] = {
                "id": instance.requested_by_department.id,
                "code": instance.requested_by_department.code,
                "name": instance.requested_by_department.name
            }
            ret['template_object'] = model_to_dict(instance.template_no)
            
            return ret
        except Exception as e:
            ret['action_required'] = "None"
            ret['requested_to_company'] = "None"
            ret['requested_to_department'] = "None"
            ret['requested_to_user'] = "None"
            ret['requested_by_user'] = "None"
            ret['requested_by_department'] = "None"
            ret['template_object'] = "None"

            return ret
    # 'company_desc', 'department_desc', 'requested_desc',
    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',
                  '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(is_action=True) &
                Q(user=id_number)
            ).order_by('level')
            
            if current_level.count() > 0: # and 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_required'] = approver
            ret['company'] = instance.requested_to_company.name
            ret['department'] = instance.requested_to_department.name
            ret['requested_by'] = instance.requested_by_user.name

            if instance.status.lower() == 'draft':
                existing_transaction = models.ChangeRequestHistory.objects.filter(
                    form_code=instance.form_code
                )
                if existing_transaction.count() > 0:
                    can_delete = False
                else:
                    can_delete = True  # hard delete

            elif instance.status.lower() == 'cancelled':
                can_delete = False
            else:
                can_delete = None

            ret['can_delete'] = can_delete

            return ret
        except Exception as e:
            ret['action_required'] = "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']