from rest_framework import serializers

from fwd_api.constant.common import ProcessType, FileCategory
from fwd_api.models import SubscriptionRequest, SubscriptionRequestFile
from fwd_api.response.ReportFileSerializer import ReportFileSerializer
from fwd_api.utils.date import FORMAT
from django.utils.translation import gettext as _
from fwd_api.utils import file as FileUtils

def i18n_for_label(data) -> list:
    if 'fields' in data and isinstance(data['fields'], list):
        return list(map(lambda field: {**field, 'label': _(field['label'])}, data['fields']))
    return []

class ReportSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    fwd_request_id = serializers.CharField(required=False)
    pages = serializers.IntegerField(read_only=True)
    # doc_type = serializers.CharField(required=False)
    created_at = serializers.DateTimeField(required=False, format=FORMAT.DD_MM_YYYY_HHMMSS.value)
    response_uri = serializers.CharField(required=False)
    data = serializers.SerializerMethodField()
    # predict_result = serializers.SerializerMethodField()

    status = serializers.CharField()
    files = serializers.SerializerMethodField()

    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return SubscriptionRequest.objects.create(**validated_data)

    def update(self, instance, validated_data):
        return instance

    def get_files(self, obj: SubscriptionRequest):

        data = SubscriptionRequestFile.objects.filter(request=obj, file_category=FileCategory.Origin.value)

        if not data:
            return None
        return ReportFileSerializer(data, many=True).data

    def get_data(self, obj: SubscriptionRequest):
        data = obj.predict_result
        sub = obj.subscription
        user_id = sub.user.id
        sync_id = sub.user.sync_id
        sub_id = sub.id            
        if int(obj.process_type) == ProcessType.FI_INVOICE.value:
            if data and 'content' in data and 'combine_results' in data['content']:
                return data['content']['combine_results']
            return ""
        if data and 'content' in data:
            model_status = data['status']
            data = data['content']
            data.pop('document_type', None)
            data['status'] = model_status

            if 'pages' in data and isinstance(data['pages'], list):
                new_data = []
                for page in data['pages']:
                    new_page_object = {
                        'page_index': page['page_index'],
                        'fields': i18n_for_label(page),
                        'image_url': FileUtils.build_media_url_v2(str(page['request_file_id']), user_id, sub_id, sync_id),
                    }

                    if 'path_image_croped' in page:
                        new_page_object['image_url'] = FileUtils.build_media_url_v2(str(page['path_image_croped']), user_id, sub_id, sync_id)
                    new_data.append(new_page_object)
                data['pages'] = new_data
        return data
