from django.shortcuts import render, get_object_or_404
from django.core.exceptions import ImproperlyConfigured
from importlib import import_module


def import_view(path):
    modules = path.split('.')
    module = '.'.join(modules[0:-1])
    view = modules[-1]

    return getattr(import_module(module), view)


def translate_url(request, url, settings):
    url_list = url.split('/')
    del url_list[-1]  # Delete empty url after last slash

    nodes = []
    leaf = None

    # 2do: DRY!
    for i, url in enumerate(url_list):
        if i != len(url_list) - 1:  # i is not last
            get_dict = {settings['node_settings'].get('slug', 'slug'): url}
            node = get_object_or_404(settings['node_settings']['model'], **get_dict)
            nodes.append(node)
        else:
            # Last url
            try:
                get_dict = {settings['node_settings'].get('slug', 'slug'): url}
                node = settings['node_settings']['model'].objects.get(**get_dict)
                nodes.append(node)
            except:
                get_dict = {settings['leaf_settings'].get('slug', 'slug'): url}
                leaf = get_object_or_404(settings['leaf_settings']['model'], **get_dict)

    if leaf:
        which_settings = 'leaf_settings'
    else:
        which_settings = 'node_settings'

    template = settings[which_settings].get('template', None)
    view = settings[which_settings].get('view', None)

    if template:
        return render(
            request,
            template,
            {
                'mptt_urls': {
                    'leaf': leaf,
                    'node': nodes[-1],
                    'nodes': nodes,
                }
            }
        )
    elif view:
        if isinstance(view, basestring):
            view = import_view(view)

        return view(
            request,
            mptt_urls={
                'leaf': leaf,
                'node': nodes[-1],
                'nodes': nodes,
            }
        )
    else:
        raise ImproperlyConfigured('Cannot find `template` or `view` value in mptt_urls settings')

@@ -450,23 +450,8 @@
 node
-s = %5B%5D%0A    leaf
  = N
@@ -561,16 +561,30 @@
 not last
+  # 2do: ugly!
 %0A       
@@ -663,23 +663,16 @@
         
- node =
  get_obj
@@ -733,39 +733,33 @@
 ict)
-%0A            nodes.append(node)
+  # 2do: Suppress output?
 %0A   
@@ -792,16 +792,40 @@
 ast url%0A
+            # 2do: DRY!%0A
         
@@ -1015,26 +1015,23 @@
     
-nodes.append(node)
+is_leaf = False
 %0A   
@@ -1143,20 +1143,20 @@
         
-leaf
+node
  = get_o
@@ -1215,16 +1215,47 @@
 et_dict)
+%0A                is_leaf = True
 %0A%0A    if
@@ -1255,16 +1255,19 @@
 %0A    if 
+is_
 leaf:%0A  
@@ -1627,94 +1627,19 @@
    '
-leaf': leaf,%0A                    'node': nodes%5B-1%5D,%0A                    'nodes': nodes
+node': node
 ,%0A  
@@ -1859,86 +1859,19 @@
    '
-leaf': leaf,%0A                'node': nodes%5B-1%5D,%0A                'nodes': nodes
+node': node
 ,%0A  

Return only current URL-related object