from django.conf import settings
from importlib import import_module
from django.utils.module_loading import import_string
from django.urls.resolvers import RegexPattern, RoutePattern
from addict import Dict
from rest_framework.views import APIView
from .endpoint import Endpoint
from django.contrib.admindocs.views import simplify_regex


class BaseAPIParser:
    """
    Class to iherit other parsers from
    """
    def __init__(self, patterns=None):
        self.patterns = patterns
        if not patterns:
            try:
                root_urlconf = import_string(settings.ROOT_URLCONF)
            except ImportError:
                # Handle a case when there's no dot in ROOT_URLCONF
                root_urlconf = import_module(settings.ROOT_URLCONF)
            if hasattr(root_urlconf, 'urls'):
                self.patterns = root_urlconf.urls.urlpatterns
            else:
                self.patterns = root_urlconf.urlpatterns
        self.parse()

    def parse(self):
        raise NotImplementedError("Inherit some parser from this class first")

    @staticmethod
    def _is_drf_pattern(pattern):
        if hasattr(pattern.callback, 'view_class'):
            return issubclass(pattern.callback.view_class, APIView)


class TreeAPIParser(BaseAPIParser):
    """
    Creates a nice tree of API
    """
    def __init__(self, *args, **kwargs):
        self.endpoints_tree = Dict()
        super().__init__(*args, **kwargs)

    def parse(self):
        self.parse_tree(self.patterns, self.endpoints_tree)

    def parse_tree(self, urlpatterns, parent_node, prefix=''):
        for pattern in urlpatterns:
            if isinstance(pattern, RegexPattern):
                child_node_name = simplify_regex(pattern._regex).strip('/') if pattern._regex else ""
                self.parse_tree(
                    urlpatterns=pattern.url_patterns,
                    parent_node=parent_node[child_node_name] if child_node_name else parent_node,
                    prefix='%s/%s' % (prefix, child_node_name)
                )

            elif isinstance(pattern, RoutePattern) and self._is_drf_pattern(pattern):
                api_endpoint = Endpoint(pattern, prefix)
                parent_node[api_endpoint.name] = api_endpoint

@@ -116,16 +116,25 @@
 _string%0A
+try:%0A    
 from dja
@@ -141,17 +141,146 @@
 ngo.urls
-.
+ import URLPattern as RegexURLPattern%0A    from django.urls import URLResolver as RegexURLResolver%0Aexcept:%0A    from django.core.url
 resolver
@@ -297,29 +297,41 @@
 egex
-Patt
+URLResolv
 er
-n
 , R
-oute
+egexURL
 Pattern
+%09    
 %0Afro
@@ -1818,17 +1818,198 @@
 egex
-Pattern):
+URLResolver):%0A                try:%0A                    regex = pattern._regex if hasattr(pattern, %22_regex%22) else pattern.pattern._regex%0A                except:%0A                    regex = %22%22
 %0A   
@@ -2054,25 +2054,16 @@
 y_regex(
-pattern._
 regex).s
@@ -2075,25 +2075,16 @@
 '/') if 
-pattern._
 regex el
@@ -2398,12 +2398,15 @@
 n, R
-oute
+egexURL
 Patt
@@ -2556,16 +2556,23 @@
  = api_endpoint%0A
+%0A%0A%0A%0A%0A%0A%0A

Revert "Revert "Revert "Works with Django 2.0"""