# Path: sitetree/fields.py
# class TreeItemChoiceField(ChoiceField):
#     """Generic sitetree item field.
#     Customized ChoiceField with TreeItems of a certain tree.
# 
#     Accepts the `tree` kwarg - tree model or alias.
#     Use `initial` kwarg to set initial sitetree item by its ID.
# 
#     """
#     template: str = 'admin/sitetree/tree/tree_combo.html'
#     root_title: str = '---------'
# 
#     def __init__(
#             self,
#             tree: 'TreeBase' = None,
#             required: bool = True,
#             widget=None,
#             label=None,
#             initial=None,
#             help_text=None,
#             *args, **kwargs
#     ):
#         super().__init__(
#             required=required, widget=widget, label=label, initial=initial,
#             help_text=help_text, *args, **kwargs)
# 
#         self.tree = None
#         self.choices_init(tree)
# 
#     def choices_init(self, tree: Optional['TreeBase']):
#         """Initialize choices for the given tree.
# 
#         :param tree:
# 
#         """
#         if not tree:
#             return
# 
#         if isinstance(tree, MODEL_TREE_CLASS):
#             tree = tree.alias
# 
#         self.tree = tree
#         self.choices = self._build_choices()
# 
#     def _build_choices(self):
#         """Build choices list runtime using 'sitetree_tree' tag"""
#         tree_token = f'sitetree_tree from "{self.tree}" template "{self.template}"'
# 
#         context_kwargs = {'current_app': 'admin'}
#         context = template.Context(context_kwargs)
#         context.update({'request': object()})
# 
#         choices_str = sitetree_tree(
#             Parser([]), Token(token_type=TOKEN_BLOCK, contents=tree_token)
#         ).render(context)
# 
#         tree_choices = [(ITEMS_FIELD_ROOT_ID, self.root_title)]
# 
#         for line in choices_str.splitlines():
#             if line.strip():
#                 splitted = line.split(':::')
#                 tree_choices.append((splitted[0], mark_safe(splitted[1])))
# 
#         return tree_choices
# 
#     def clean(self, value):
#         if not value:
#             return None
# 
#         try:
#             return MODEL_TREE_ITEM_CLASS.objects.get(pk=value)
# 
#         except MODEL_TREE_ITEM_CLASS.DoesNotExist:
#             return None
# 
# Path: sitetree/settings.py
# MODEL_TREE: str = getattr(settings, 'SITETREE_MODEL_TREE', 'sitetree.Tree')
# 
# MODEL_TREE_ITEM: str = getattr(settings, 'SITETREE_MODEL_TREE_ITEM', 'sitetree.TreeItem')
# 
# Path: sitetree/utils.py
# def get_tree_model() -> Type['TreeBase']:
#     """Returns the Tree model, set for the project."""
#     return get_model_class('MODEL_TREE')
# 
# def get_tree_item_model() -> Type['TreeItemBase']:
#     """Returns the TreeItem model, set for the project."""
#     return get_model_class('MODEL_TREE_ITEM')
# 
# def get_app_n_model(settings_entry_name: str) -> Tuple[str, str]:
#     """Returns tuple with application and tree[item] model class names.
# 
#     :param settings_entry_name:
# 
#     """
#     try:
#         app_name, model_name = getattr(settings, settings_entry_name).split('.')
# 
#     except ValueError:
#         raise ImproperlyConfigured(
#             f'`SITETREE_{settings_entry_name}` must have the following format: `app_name.model_name`.')
# 
#     return app_name, model_name


from typing import Tuple, Type, Optional
from django import forms
from django.conf import settings as django_settings
from django.urls import re_path, path
from django.contrib import admin
from django.contrib import messages
from django.contrib.admin.sites import NotRegistered
from django.http import HttpResponseRedirect, HttpRequest, HttpResponse
from django.urls import get_urlconf, get_resolver
from django.utils.translation import gettext_lazy as _
from .fields import TreeItemChoiceField
from .settings import MODEL_TREE, MODEL_TREE_ITEM
from .utils import get_tree_model, get_tree_item_model, get_app_n_model
    from .models import TreeItemBase, TreeBase  # noqa
        from smuggler.views import dump_to_response


SMUGGLER_INSTALLED = 'smuggler' in django_settings.INSTALLED_APPS

MODEL_TREE_CLASS = get_tree_model()
MODEL_TREE_ITEM_CLASS = get_tree_item_model()

_TREE_ADMIN = lambda: TreeAdmin
_ITEM_ADMIN = lambda: TreeItemAdmin


def get_model_url_name(model_nfo: Tuple[str, str], page: str, with_namespace: bool = False) -> str:
    """Returns a URL for a given Tree admin page type."""
    prefix = ''
    if with_namespace:
        prefix = 'admin:'
    return (f'{prefix}%s_{page}' % '%s_%s' % model_nfo).lower()


def get_tree_url_name(page: str, with_namespace: bool = False) -> str:
    """Returns a URL for a given Tree admin page type."""
    return get_model_url_name(get_app_n_model('MODEL_TREE'), page, with_namespace)


def get_tree_item_url_name(page: str, with_namespace: bool = False) -> str:
    """Returns a URL for a given Tree Item admin page type."""
    return get_model_url_name(get_app_n_model('MODEL_TREE_ITEM'), page, with_namespace)


_TREE_URLS = {

# Path: sitetree/fields.py
# class TreeItemChoiceField(ChoiceField):
#     """Generic sitetree item field.
#     Customized ChoiceField with TreeItems of a certain tree.
# 
#     Accepts the `tree` kwarg - tree model or alias.
#     Use `initial` kwarg to set initial sitetree item by its ID.
# 
#     """
#     template: str = 'admin/sitetree/tree/tree_combo.html'
#     root_title: str = '---------'
# 
#     def __init__(
#             self,
#             tree: 'TreeBase' = None,
#             required: bool = True,
#             widget=None,
#             label=None,
#             initial=None,
#             help_text=None,
#             *args, **kwargs
#     ):
#         super().__init__(
#             required=required, widget=widget, label=label, initial=initial,
#             help_text=help_text, *args, **kwargs)
# 
#         self.tree = None
#         self.choices_init(tree)
# 
#     def choices_init(self, tree: Optional['TreeBase']):
#         """Initialize choices for the given tree.
# 
#         :param tree:
# 
#         """
#         if not tree:
#             return
# 
#         if isinstance(tree, MODEL_TREE_CLASS):
#             tree = tree.alias
# 
#         self.tree = tree
#         self.choices = self._build_choices()
# 
#     def _build_choices(self):
#         """Build choices list runtime using 'sitetree_tree' tag"""
#         tree_token = f'sitetree_tree from "{self.tree}" template "{self.template}"'
# 
#         context_kwargs = {'current_app': 'admin'}
#         context = template.Context(context_kwargs)
#         context.update({'request': object()})
# 
#         choices_str = sitetree_tree(
#             Parser([]), Token(token_type=TOKEN_BLOCK, contents=tree_token)
#         ).render(context)
# 
#         tree_choices = [(ITEMS_FIELD_ROOT_ID, self.root_title)]
# 
#         for line in choices_str.splitlines():
#             if line.strip():
#                 splitted = line.split(':::')
#                 tree_choices.append((splitted[0], mark_safe(splitted[1])))
# 
#         return tree_choices
# 
#     def clean(self, value):
#         if not value:
#             return None
# 
#         try:
#             return MODEL_TREE_ITEM_CLASS.objects.get(pk=value)
# 
#         except MODEL_TREE_ITEM_CLASS.DoesNotExist:
#             return None
# 
# Path: sitetree/settings.py
# MODEL_TREE: str = getattr(settings, 'SITETREE_MODEL_TREE', 'sitetree.Tree')
# 
# MODEL_TREE_ITEM: str = getattr(settings, 'SITETREE_MODEL_TREE_ITEM', 'sitetree.TreeItem')
# 
# Path: sitetree/utils.py
# def get_tree_model() -> Type['TreeBase']:
#     """Returns the Tree model, set for the project."""
#     return get_model_class('MODEL_TREE')
# 
# def get_tree_item_model() -> Type['TreeItemBase']:
#     """Returns the TreeItem model, set for the project."""
#     return get_model_class('MODEL_TREE_ITEM')
# 
# def get_app_n_model(settings_entry_name: str) -> Tuple[str, str]:
#     """Returns tuple with application and tree[item] model class names.
# 
#     :param settings_entry_name:
# 
#     """
#     try:
#         app_name, model_name = getattr(settings, settings_entry_name).split('.')
# 
#     except ValueError:
#         raise ImproperlyConfigured(
#             f'`SITETREE_{settings_entry_name}` must have the following format: `app_name.model_name`.')
# 
#     return app_name, model_name


# Path: sitetree/admin.py
from typing import Tuple, Type, Optional
from django import forms
from django.conf import settings as django_settings
from django.urls import re_path, path
from django.contrib import admin
from django.contrib import messages
from django.contrib.admin.sites import NotRegistered
from django.http import HttpResponseRedirect, HttpRequest, HttpResponse
from django.urls import get_urlconf, get_resolver
from django.utils.translation import gettext_lazy as _
from .fields import TreeItemChoiceField
from .settings import MODEL_TREE, MODEL_TREE_ITEM
from .utils import get_tree_model, get_tree_item_model, get_app_n_model
    from .models import TreeItemBase, TreeBase  # noqa
        from smuggler.views import dump_to_response



SMUGGLER_INSTALLED = 'smuggler' in django_settings.INSTALLED_APPS

MODEL_TREE_CLASS = get_tree_model()
MODEL_TREE_ITEM_CLASS = get_tree_item_model()

_TREE_ADMIN = lambda: TreeAdmin
_ITEM_ADMIN = lambda: TreeItemAdmin


def get_model_url_name(model_nfo: Tuple[str, str], page: str, with_namespace: bool = False) -> str:
    """Returns a URL for a given Tree admin page type."""
    prefix = ''
    if with_namespace:
        prefix = 'admin:'
    return (f'{prefix}%s_{page}' % '%s_%s' % model_nfo).lower()


def get_tree_url_name(page: str, with_namespace: bool = False) -> str:
    """Returns a URL for a given Tree admin page type."""
    return get_model_url_name(get_app_n_model('MODEL_TREE'), page, with_namespace)


def get_tree_item_url_name(page: str, with_namespace: bool = False) -> str:
    """Returns a URL for a given Tree Item admin page type."""
    return get_model_url_name(get_app_n_model('MODEL_TREE_ITEM'), page, with_namespace)


_TREE_URLS = {

    'app': get_app_n_model('MODEL_TREE')[0],