# 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 dictionize_list_for_formsets(self):
        d = {}
        for (counter, data) in enumerate(self.objects):
            d.update(dict([(unicode("form-"+str(counter)+"-"+str(k)), v) for (k,v) in data.items()]))
        d.update({'form-TOTAL_FORMS': unicode(counter+1), 'form-INITIAL_FORMS': u'0', 'form-MAX_NUM_FORMS': u''})
        self.objects = d

    def remove_excluded_fields(self):
        for object in self.objects:
            for field in object.keys():
                if self.selected_fields and not field in self.selected_fields:
                    del object[field]
                if field in self.excluded_fields:
                    del object[field]

    def reverse_map_fields(self, objects=None):
        if not objects:
            objects = self.objects
        if not self.map_fields:
            return
        for k,v in self.map_fields.items():
            source, target = {}, {}
            source_keys = v.split(SEPARATOR)
            target_keys = k.split(SEPARATOR)
            try:
                source = traverse_dict(objects[0], source_keys, return_parent=True)
            except KeyError:
                continue
            for obj in objects:

# 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 dictionize_list_for_formsets(self):
        d = {}
        for (counter, data) in enumerate(self.objects):
            d.update(dict([(unicode("form-"+str(counter)+"-"+str(k)), v) for (k,v) in data.items()]))
        d.update({'form-TOTAL_FORMS': unicode(counter+1), 'form-INITIAL_FORMS': u'0', 'form-MAX_NUM_FORMS': u''})
        self.objects = d

    def remove_excluded_fields(self):
        for object in self.objects:
            for field in object.keys():
                if self.selected_fields and not field in self.selected_fields:
                    del object[field]
                if field in self.excluded_fields:
                    del object[field]

    def reverse_map_fields(self, objects=None):
        if not objects:
            objects = self.objects
        if not self.map_fields:
            return
        for k,v in self.map_fields.items():
            source, target = {}, {}
            source_keys = v.split(SEPARATOR)
            target_keys = k.split(SEPARATOR)
            try:
                source = traverse_dict(objects[0], source_keys, return_parent=True)
            except KeyError:
                continue
            for obj in objects:

                create_tree_with_val(obj, target_keys, source[source_keys[-1]])