# Path: mongonaut/exceptions.py
# class NoMongoAdminSpecified(Exception):
#     """ Called when no MongoAdmin is specified. Unlikely to ever be called."""
#     pass
# 
# Path: mongonaut/forms/form_utils.py
# def has_digit(string_or_list, sep="_"):
#     """
#     Given a string or a list will return true if the last word or
#     element is a digit.  sep is used when a string is given to know
#     what separates one word from another.
#     """
#     if isinstance(string_or_list, (tuple, list)):
#         list_length = len(string_or_list)
#         if list_length:
#             return six.text_type(string_or_list[-1]).isdigit()
#         else:
#             return False
#     else:
#         return has_digit(string_or_list.split(sep))
# 
# Path: mongonaut/forms/form_utils.py
# def make_key(*args, **kwargs):
#     """
#     Given any number of lists and strings will join them in order as one
#     string separated by the sep kwarg.  sep defaults to u"_".
# 
#     Add exclude_last_string=True as a kwarg to exclude the last item in a
#     given string after being split by sep.  Note if you only have one word
#     in your string you can end up getting an empty string.
# 
#     Example uses:
# 
#     >>> from mongonaut.forms.form_utils import make_key
#     >>> make_key('hi', 'my', 'firend')
#     >>> u'hi_my_firend'
# 
#     >>> make_key('hi', 'my', 'firend', sep='i')
#     >>> 'hiimyifirend'
# 
#     >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i')
#     >>> 'hiimyifirendithisibeiwhat'
# 
#     >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'])
#     >>> u'hi_my_firend_this_be_what'
# 
#     """
#     sep = kwargs.get('sep', u"_")
#     exclude_last_string = kwargs.get('exclude_last_string', False)
#     string_array = []
# 
#     for arg in args:
#         if isinstance(arg, list):
#             string_array.append(six.text_type(sep.join(arg)))
#         else:
#             if exclude_last_string:
#                 new_key_array = arg.split(sep)[:-1]
#                 if len(new_key_array) > 0:
#                     string_array.append(make_key(new_key_array))
#             else:
#                 string_array.append(six.text_type(arg))
#     return sep.join(string_array)
# 
# Path: mongonaut/utils.py
# def translate_value(document_field, form_value):
#     """
#     Given a document_field and a form_value this will translate the value
#     to the correct result for mongo to use.
#     """
#     value = form_value
#     if isinstance(document_field, ReferenceField):
#         value = document_field.document_type.objects.get(id=form_value) if form_value else None
#     return value
# 
# Path: mongonaut/utils.py
# def trim_field_key(document, field_key):
#     """
#     Returns the smallest delimited version of field_key that
#     is an attribute on document.
# 
#     return (key, left_over_array)
#     """
#     trimming = True
#     left_over_key_values = []
#     current_key = field_key
#     while trimming and current_key:
#         if hasattr(document, current_key):
#             trimming = False
#         else:
#             key_array = current_key.split("_")
#             left_over_key_values.append(key_array.pop())
#             current_key = u"_".join(key_array)
# 
#     left_over_key_values.reverse()
#     return current_key, left_over_key_values


import types
from importlib import import_module
from django.conf import settings
from django.contrib import messages
from django.http import HttpResponseForbidden
from mongoengine.fields import EmbeddedDocumentField
from mongonaut.exceptions import NoMongoAdminSpecified
from mongonaut.forms import MongoModelForm
from mongonaut.forms.form_utils import has_digit
from mongonaut.forms.form_utils import make_key
from mongonaut.utils import translate_value
from mongonaut.utils import trim_field_key
        remaining_key = make_key(remaining_key_array)

        if current_key.lower() == 'id':
            raise KeyError(u"Mongonaut does not work with models which have fields beginning with id_")

        # Create boolean checks to make processing document easier
        is_embedded_doc = (isinstance(document._fields.get(current_key, None), EmbeddedDocumentField)
                          if hasattr(document, '_fields') else False)
        is_list = not key_array_digit is None
        key_in_fields = current_key in document._fields.keys() if hasattr(document, '_fields') else False

        # This ensures you only go through each documents keys once, and do not duplicate data
        if key_in_fields:
            if is_embedded_doc:
                self.set_embedded_doc(document, form_key, current_key, remaining_key)
            elif is_list:
                self.set_list_field(document, form_key, current_key, remaining_key, key_array_digit)
            else:
                value = translate_value(document._fields[current_key],
                                        self.form.cleaned_data[form_key])
                setattr(document, current_key, value)

    def set_embedded_doc(self, document, form_key, current_key, remaining_key):
        """Get the existing embedded document if it exists, else created it."""

        embedded_doc = getattr(document, current_key, False)
        if not embedded_doc:
            embedded_doc = document._fields[current_key].document_type_obj()

        new_key, new_remaining_key_array = trim_field_key(embedded_doc, remaining_key)

# Path: mongonaut/exceptions.py
# class NoMongoAdminSpecified(Exception):
#     """ Called when no MongoAdmin is specified. Unlikely to ever be called."""
#     pass
# 
# Path: mongonaut/forms/form_utils.py
# def has_digit(string_or_list, sep="_"):
#     """
#     Given a string or a list will return true if the last word or
#     element is a digit.  sep is used when a string is given to know
#     what separates one word from another.
#     """
#     if isinstance(string_or_list, (tuple, list)):
#         list_length = len(string_or_list)
#         if list_length:
#             return six.text_type(string_or_list[-1]).isdigit()
#         else:
#             return False
#     else:
#         return has_digit(string_or_list.split(sep))
# 
# Path: mongonaut/forms/form_utils.py
# def make_key(*args, **kwargs):
#     """
#     Given any number of lists and strings will join them in order as one
#     string separated by the sep kwarg.  sep defaults to u"_".
# 
#     Add exclude_last_string=True as a kwarg to exclude the last item in a
#     given string after being split by sep.  Note if you only have one word
#     in your string you can end up getting an empty string.
# 
#     Example uses:
# 
#     >>> from mongonaut.forms.form_utils import make_key
#     >>> make_key('hi', 'my', 'firend')
#     >>> u'hi_my_firend'
# 
#     >>> make_key('hi', 'my', 'firend', sep='i')
#     >>> 'hiimyifirend'
# 
#     >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i')
#     >>> 'hiimyifirendithisibeiwhat'
# 
#     >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'])
#     >>> u'hi_my_firend_this_be_what'
# 
#     """
#     sep = kwargs.get('sep', u"_")
#     exclude_last_string = kwargs.get('exclude_last_string', False)
#     string_array = []
# 
#     for arg in args:
#         if isinstance(arg, list):
#             string_array.append(six.text_type(sep.join(arg)))
#         else:
#             if exclude_last_string:
#                 new_key_array = arg.split(sep)[:-1]
#                 if len(new_key_array) > 0:
#                     string_array.append(make_key(new_key_array))
#             else:
#                 string_array.append(six.text_type(arg))
#     return sep.join(string_array)
# 
# Path: mongonaut/utils.py
# def translate_value(document_field, form_value):
#     """
#     Given a document_field and a form_value this will translate the value
#     to the correct result for mongo to use.
#     """
#     value = form_value
#     if isinstance(document_field, ReferenceField):
#         value = document_field.document_type.objects.get(id=form_value) if form_value else None
#     return value
# 
# Path: mongonaut/utils.py
# def trim_field_key(document, field_key):
#     """
#     Returns the smallest delimited version of field_key that
#     is an attribute on document.
# 
#     return (key, left_over_array)
#     """
#     trimming = True
#     left_over_key_values = []
#     current_key = field_key
#     while trimming and current_key:
#         if hasattr(document, current_key):
#             trimming = False
#         else:
#             key_array = current_key.split("_")
#             left_over_key_values.append(key_array.pop())
#             current_key = u"_".join(key_array)
# 
#     left_over_key_values.reverse()
#     return current_key, left_over_key_values


# Path: mongonaut/mixins.py
import types
from importlib import import_module
from django.conf import settings
from django.contrib import messages
from django.http import HttpResponseForbidden
from mongoengine.fields import EmbeddedDocumentField
from mongonaut.exceptions import NoMongoAdminSpecified
from mongonaut.forms import MongoModelForm
from mongonaut.forms.form_utils import has_digit
from mongonaut.forms.form_utils import make_key
from mongonaut.utils import translate_value
from mongonaut.utils import trim_field_key

        remaining_key = make_key(remaining_key_array)

        if current_key.lower() == 'id':
            raise KeyError(u"Mongonaut does not work with models which have fields beginning with id_")

        # Create boolean checks to make processing document easier
        is_embedded_doc = (isinstance(document._fields.get(current_key, None), EmbeddedDocumentField)
                          if hasattr(document, '_fields') else False)
        is_list = not key_array_digit is None
        key_in_fields = current_key in document._fields.keys() if hasattr(document, '_fields') else False

        # This ensures you only go through each documents keys once, and do not duplicate data
        if key_in_fields:
            if is_embedded_doc:
                self.set_embedded_doc(document, form_key, current_key, remaining_key)
            elif is_list:
                self.set_list_field(document, form_key, current_key, remaining_key, key_array_digit)
            else:
                value = translate_value(document._fields[current_key],
                                        self.form.cleaned_data[form_key])
                setattr(document, current_key, value)

    def set_embedded_doc(self, document, form_key, current_key, remaining_key):
        """Get the existing embedded document if it exists, else created it."""

        embedded_doc = getattr(document, current_key, False)
        if not embedded_doc:
            embedded_doc = document._fields[current_key].document_type_obj()

        new_key, new_remaining_key_array = trim_field_key(embedded_doc, remaining_key)

        self.process_document(embedded_doc, form_key, make_key(new_key, new_remaining_key_array))