# Path: riv/utils.py
# def traverse_dict(d, keys, return_parent=False):
#     if return_parent:
#         # Remove the last key element and set return_parent to False
#         # for recursive calls.
#         keys = keys[:-1]
#         return_parent = False
#     if isinstance(d, dict) and len(keys) > 0:
#         if d.has_key(keys[0]):
#             return traverse_dict(d[keys[0]], keys[1:], return_parent)
#         else:
#             raise KeyError("Traversing the dictionary failed on key: %s" % keys[0])
#     elif isinstance(d, list) and len(keys) == 1:
#         try:
#             if isinstance(d[0], dict):
#                 try:
#                     return [i[keys[0]] for i in d]
#                 except KeyError, e:
#                     raise KeyError("Traversing the dictionary failed on key: %s" % keys[0])
#         except IndexError, e:
#             raise KeyError("Traversing the dictionary failed on key: %s" % keys[0])
#     else:
#         # if "keys" is specified the user requested to further traverse
#         # the dictionary. This fails so we return None. In any other
#         # case we arrived and return the value. 
#         if keys:
#             raise KeyError("Traversing the dictionary failed on key: %s" % keys[0])
#         else:
#             return d
# 
# def create_tree_with_val(d, keys, val):
#     if not keys:
#         return
#     if len(keys) == 1:
#         d[keys[0]] = val
#     if not d.has_key(keys[0]):
#         d[keys[0]] = {}
#     create_tree_with_val(d[keys[0]], keys[1:], val)
# 
# def get_url_for_object(api_name, obj, extra_id=None):
#     try:
#         if extra_id:
#             return reverse('object-%s-%s' % (api_name, obj._meta), kwargs={'id': extra_id})
#         else:
#             return reverse('object-%s-%s' % (api_name, obj._meta), kwargs={'id': obj.id})
#     except NoReverseMatch:
#         return obj._get_pk_val()


import json
from StringIO import StringIO
from django.db.models import Model
from django.core.serializers import python, json
from django.core.serializers.base import SerializationError
from django.core.urlresolvers import reverse, NoReverseMatch
from django.utils.encoding import smart_unicode, is_protected_type
from riv.utils import traverse_dict, create_tree_with_val, get_url_for_object
    def _get_serialize_options_for_subfield(self, name):
            fields, exclude, maps, inline = None, None, {}, None
            field_option_name = name + SEPARATOR
            if self.selected_fields:
                fields = [i.replace(field_option_name,'') for i in self.selected_fields if i.startswith(field_option_name)]
            if self.excluded_fields:
                exclude = [i.replace(field_option_name,'') for i in self.excluded_fields if i.startswith(field_option_name)]
            if self.inline:
                inline = [i.replace(field_option_name,'') for i in self.inline if i.startswith(field_option_name)]
            if self.map_fields:
                for k,v in self.map_fields.items():
                    if k.startswith(field_option_name) and v.startswith(field_option_name):
                        maps[k.replace(field_option_name, '')] = v.replace(field_option_name, '')
            return fields or None, exclude or None, maps, inline

    def _map_field(self, key, value):
        if self._current.has_key(key):
            self._current[value] = self._current[key]
            del self._current[key]
        elif SEPARATOR in key and self._current.has_key(key.split(SEPARATOR)[0]):
            key_list = key.split(SEPARATOR)

            # Skip if the FK or M2M relation is blank.
            if not self._current[key_list[0]]:
                return

            if SEPARATOR in value:
                value_list = value.split(SEPARATOR)
                # Test if the key is valid to generate nice errors.
                try:

# Path: riv/utils.py
# def traverse_dict(d, keys, return_parent=False):
#     if return_parent:
#         # Remove the last key element and set return_parent to False
#         # for recursive calls.
#         keys = keys[:-1]
#         return_parent = False
#     if isinstance(d, dict) and len(keys) > 0:
#         if d.has_key(keys[0]):
#             return traverse_dict(d[keys[0]], keys[1:], return_parent)
#         else:
#             raise KeyError("Traversing the dictionary failed on key: %s" % keys[0])
#     elif isinstance(d, list) and len(keys) == 1:
#         try:
#             if isinstance(d[0], dict):
#                 try:
#                     return [i[keys[0]] for i in d]
#                 except KeyError, e:
#                     raise KeyError("Traversing the dictionary failed on key: %s" % keys[0])
#         except IndexError, e:
#             raise KeyError("Traversing the dictionary failed on key: %s" % keys[0])
#     else:
#         # if "keys" is specified the user requested to further traverse
#         # the dictionary. This fails so we return None. In any other
#         # case we arrived and return the value. 
#         if keys:
#             raise KeyError("Traversing the dictionary failed on key: %s" % keys[0])
#         else:
#             return d
# 
# def create_tree_with_val(d, keys, val):
#     if not keys:
#         return
#     if len(keys) == 1:
#         d[keys[0]] = val
#     if not d.has_key(keys[0]):
#         d[keys[0]] = {}
#     create_tree_with_val(d[keys[0]], keys[1:], val)
# 
# def get_url_for_object(api_name, obj, extra_id=None):
#     try:
#         if extra_id:
#             return reverse('object-%s-%s' % (api_name, obj._meta), kwargs={'id': extra_id})
#         else:
#             return reverse('object-%s-%s' % (api_name, obj._meta), kwargs={'id': obj.id})
#     except NoReverseMatch:
#         return obj._get_pk_val()


# Path: riv/serializers/base_serializer.py
import json
from StringIO import StringIO
from django.db.models import Model
from django.core.serializers import python, json
from django.core.serializers.base import SerializationError
from django.core.urlresolvers import reverse, NoReverseMatch
from django.utils.encoding import smart_unicode, is_protected_type
from riv.utils import traverse_dict, create_tree_with_val, get_url_for_object

    def _get_serialize_options_for_subfield(self, name):
            fields, exclude, maps, inline = None, None, {}, None
            field_option_name = name + SEPARATOR
            if self.selected_fields:
                fields = [i.replace(field_option_name,'') for i in self.selected_fields if i.startswith(field_option_name)]
            if self.excluded_fields:
                exclude = [i.replace(field_option_name,'') for i in self.excluded_fields if i.startswith(field_option_name)]
            if self.inline:
                inline = [i.replace(field_option_name,'') for i in self.inline if i.startswith(field_option_name)]
            if self.map_fields:
                for k,v in self.map_fields.items():
                    if k.startswith(field_option_name) and v.startswith(field_option_name):
                        maps[k.replace(field_option_name, '')] = v.replace(field_option_name, '')
            return fields or None, exclude or None, maps, inline

    def _map_field(self, key, value):
        if self._current.has_key(key):
            self._current[value] = self._current[key]
            del self._current[key]
        elif SEPARATOR in key and self._current.has_key(key.split(SEPARATOR)[0]):
            key_list = key.split(SEPARATOR)

            # Skip if the FK or M2M relation is blank.
            if not self._current[key_list[0]]:
                return

            if SEPARATOR in value:
                value_list = value.split(SEPARATOR)
                # Test if the key is valid to generate nice errors.
                try:

                    traverse_dict(self._current, key_list)