from .base import BaseDocument, DocumentMeta, ObjectIdField
from .exceptions import OperationError
from .query import Query
import pymongo

__all__ = ['Document', 'EmbeddedDocument']

class Document(BaseDocument):
    __metaclass__ = DocumentMeta

    id = ObjectIdField(db_field='_id')
    objects = Query(None, None)

    def save(self, safe=True, insert=False):
        self.validate()

        doc = self.to_mongo()

        try:
            collection = self.__class__.objects._collection
   
            if insert:
                object_id = collection.insert(doc, safe=safe)
            else:
                object_id = collection.save(doc, safe=safe)
        except pymongo.errors.OperationFailure, err:
            raise OperationError(unicode(err))

        self['id'] = object_id

    def delete(self, safe=False):
        object_id = self._fields['id'].to_mongo(self.id)

        try:
            self.__class__.objects.filter_by(id=object_id).delete(safe=safe)
        except pymongo.errors.OperationFailure, err:
            raise OperationError(unicode(err))

    def reload(self):
        doc = self.__class__.objects.filter_by(id=self.id)._one()
        
        for field in self._fields.itervalues():
            setattr(self, field.name, field.to_python(doc.get(field.db_field)))

    @classmethod 
    def drop_collection(cls):
        cls.objects._collection.drop()

class EmbeddedDocument(BaseDocument):
    __metaclass__ = DocumentMeta
    _meta = {'embedded': True}
@@ -1093,34 +1093,35 @@
 self):%0A        d
-oc
+ata
  = self.__class_
@@ -1159,24 +1159,16 @@
 ._one()%0A
-        
 %0A       
@@ -1191,19 +1191,25 @@
 lf._
+_class__._
 fields.
-iter
 valu
@@ -1230,22 +1230,62 @@
     
-setattr(self, 
+if field.db_field in data:%0A                self._data%5B
 fiel
@@ -1290,17 +1290,19 @@
 eld.name
-,
+%5D =
  field.t
@@ -1315,15 +1315,12 @@
 on(d
-oc.get(
+ata%5B
 fiel
@@ -1329,18 +1329,17 @@
 db_field
-))
+%5D
 )%0A%0A    @

fix reload function