from app.entities import models
from rest_framework import serializers
from django.db.models import Q


class headers(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=instance.form_code) &
            (Q(action='') | Q(action=None))
        ).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['requested_to_company'] = instance.requested_to_company.name
        ret['requested_to_department'] = instance.requested_to_department.name
        ret['requested_by_user'] = instance.requested_by_user.name
        ret['requested_to_target_date'] = instance.requested_to_target_date.strftime('%Y-%m-%d-%H:%M:%S')
        # ret['created'] = instance.created.strftime('%Y-%m-%d-%H:%M:%S')
        ret['created'] = instance.created.strftime('%Y-%m-%d-%H:%M:%S')
        ret['action'] = approver
        # ret['requested_to_target_date'] = instance.requested_to_target_date.strftime('%Y-%m-%d-%H:%M:%S')
        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 = (
            'requested_to_template_id',
            'requested_to_template_name',
            'requested_to_company',
            'requested_to_department',
            'requested_by_user',
            'status',
            'requested_to_priority',
            # 'action',
            'created',
            'requested_to_target_date'
        )
