from django.conf import settings
from importlib import import_module
from django.utils.module_loading import import_string
try:
    from django.urls import URLPattern as RegexURLPattern
    from django.urls import URLResolver as RegexURLResolver
except:
    from django.core.urlresolvers import RegexURLResolver, RegexURLPattern	    
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, RegexURLResolver):
                try:
                    regex = pattern._regex if hasattr(pattern, "_regex") else pattern.pattern._regex
                except:
                    regex = ""
                child_node_name = simplify_regex(regex).strip('/') if 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, RegexURLPattern) and self._is_drf_pattern(pattern):
                api_endpoint = Endpoint(pattern, prefix)
                parent_node[api_endpoint.name] = api_endpoint








@@ -116,25 +116,16 @@
 _string%0A
-try:%0A    
 from dja
@@ -136,138 +136,9 @@
 urls
- import URLPattern as RegexURLPattern%0A    from django.urls import URLResolver as RegexURLResolver%0Aexcept:%0A    from django.core.url
+.
 reso
@@ -159,41 +159,29 @@
 egex
-URLResolv
+Patt
 er
+n
 , R
-egexURL
+oute
 Pattern
-%09    
 %0Afro
@@ -1668,198 +1668,17 @@
 egex
-URLResolver):%0A                try:%0A                    regex = pattern._regex if hasattr(pattern, %22_regex%22) else pattern.pattern._regex%0A                except:%0A                    regex = %22%22
+Pattern):
 %0A   
@@ -1723,16 +1723,25 @@
 y_regex(
+pattern._
 regex).s
@@ -1753,16 +1753,25 @@
 '/') if 
+pattern._
 regex el
@@ -2085,15 +2085,12 @@
 n, R
-egexURL
+oute
 Patt
@@ -2248,15 +2248,8 @@
 ndpoint%0A
-%0A%0A%0A%0A%0A%0A%0A

Revert "Revert "Works with Django 2.0""