from importlib import import_module

from drf_spectacular import plumbing
from drf_spectacular.openapi import AutoSchema as BaseAutoSchema


def get_lib_doc_excludes():
    """
    Исключения, классы в которых не будут учитываться doc_string
    для description ручек
    """
    from lms.core.views import mixins, viewsets
    return [
        *plumbing.get_lib_doc_excludes(),
        *[getattr(viewsets, c) for c in dir(viewsets) if c.endswith('ViewSet')],
        *[getattr(mixins, c) for c in dir(mixins) if c.endswith('Mixin')],
    ]


def postprocess_schema_title(result, generator, **kwargs):
    """
    Выставляет заголовок схемы в соответствии с urlconf
    """
    request = kwargs.get('request', None)
    if not request:
        return result

    info = result.get('info', {})

    urlconf = generator.urlconf
    if urlconf:
        if isinstance(urlconf, str):
            urls = import_module(urlconf)
        else:
            urls = urlconf

        app_name = getattr(urls, 'app_name', None)
        info['title'] = 'LMS {}'.format(app_name.upper())

    return result


class AutoSchema(BaseAutoSchema):
    def get_summary(self):
        return getattr(self.view, 'schema_summary', None)

    def _allows_filters(self):
        if getattr(self.view, 'filter_backends', None) is None:
            return False
        if hasattr(self.view, 'action'):
            return self.view.action in ["list"]

        return super()._allows_filters()
