from rest_framework import serializers

from fwd_api.constant.common import MAX_NUMBER_OF_TEMPLATE_DATA_BOX, MAX_NUMBER_OF_TEMPLATE_ANCHOR_BOX, \
    NUMBER_OF_ITEM_IN_A_BOX, ESCAPE_VALUE
from fwd_api.exception.exceptions import InvalidException
from fwd_api.utils import ProcessUtil


class CreateTemplateRequest(serializers.Serializer):
    template_name = serializers.CharField(required=True, max_length=255, allow_blank=False)
    data_box_names = serializers.CharField(required=True, max_length=9000, allow_blank=False)
    data_boxs = serializers.CharField(required=True, max_length=1000, allow_blank=False)
    anchor_boxs = serializers.CharField(required=True, max_length=255, allow_blank=False)

    def validate(self, attrs):
        b_names = attrs['data_box_names'].split(ESCAPE_VALUE)
        lenn: int = len(b_names)
        ProcessUtil.validate_duplicate(b_names)
        for n in b_names:
            if len(n) > 255:
                raise InvalidException(excArgs="box_label")
        data_boxs = ProcessUtil.to_box_list(attrs['data_boxs'])
        anchor_boxs = ProcessUtil.to_box_list(attrs['anchor_boxs'])
        ProcessUtil.validate_box(data_boxs, MAX_NUMBER_OF_TEMPLATE_DATA_BOX, NUMBER_OF_ITEM_IN_A_BOX, lenn)
        ProcessUtil.validate_box(anchor_boxs, MAX_NUMBER_OF_TEMPLATE_ANCHOR_BOX, NUMBER_OF_ITEM_IN_A_BOX, MAX_NUMBER_OF_TEMPLATE_ANCHOR_BOX)

        nb_data = []
        for d, name in zip(data_boxs, b_names):
            nb_data.append({
                'coordinates': ",".join(d),
                'name': name
            })
        attrs['data_boxs'] = nb_data
        attrs['anchor_boxs'] = anchor_boxs
        return attrs
