import coreapi
from drf_yasg.generators import OpenAPISchemaGenerator


def get_coreapi_type(form_type):
    mapping = {
        'boolean': 'boolean',
        'nullboolean': 'boolean',
        'integer': 'integer',
        'suggest': 'integer',
        'modelchoice': 'integer',
        'decimal': 'number',
        'grid': 'array',
        'multiplechoice': 'array',
        'multiplesuggest': 'array',
        'modelmultiplechoice': 'array',
    }
    return mapping.get(form_type, 'string')


class FemidaSchemaGenerator(OpenAPISchemaGenerator):

    def get_serializer_fields(self, path, method, view):
        if (hasattr(view, 'get_validator_object')
                and method in ('PUT', 'PATCH', 'POST')):
            try:
                validator = view.get_validator_object()
            except Exception:
                # TODO: MessageListCreateView падает с
                # `No Candidate matches the given query`
                return []

            if validator is None:
                return []

            fields = []
            structure = validator.structure_as_dict()
            for field_data in structure.values():
                if field_data.get('readonly'):
                    continue
                fields.append(
                    coreapi.Field(
                        name=field_data['name'],
                        location='form',
                        required=field_data.get('required', False),
                        type=get_coreapi_type(field_data.get('type')),
                    )
                )
            return fields

        return super().get_serializer_fields(
            path=path,
            method=method,
            view=view,
        )
