# Path: mongonaut/views.py
# class DocumentDetailView(MongonautViewMixin, TemplateView):
#     """ :args: <app_label> <document_name> <id> """
#     template_name = "mongonaut/document_detail.html"
#     permission = 'has_view_permission'
# 
#     def get_context_data(self, **kwargs):
#         context = super(DocumentDetailView, self).get_context_data(**kwargs)
#         self.set_mongoadmin()
#         context = self.set_permissions_in_context(context)
#         self.document_type = getattr(self.models, self.document_name)
#         self.ident = self.kwargs.get('id')
#         self.document = self.document_type.objects.get(pk=self.ident)
# 
#         context['document'] = self.document
#         context['app_label'] = self.app_label
#         context['document_name'] = self.document_name
#         context['keys'] = ['id', ]
#         context['embedded_documents'] = []
#         context['list_fields'] = []
#         for key in sorted([x for x in self.document._fields.keys() if x != 'id']):
#             # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view
#             # Note - This is the challenge part, right? :)
#             if isinstance(self.document._fields[key], EmbeddedDocumentField):
#                 context['embedded_documents'].append(key)
#                 continue
#             if isinstance(self.document._fields[key], ListField):
#                 context['list_fields'].append(key)
#                 continue
#             context['keys'].append(key)
#         return context
# 
# Path: examples/blog/articles/models.py
# class Post(Document):
#     # See Post.title.max_length to make validation better!
#     title = StringField(max_length=120, required=True, unique=True)
#     content = StringField(default="I am default content")
#     author = ReferenceField(User, required=True)
#     created_date = DateTimeField()
#     published = BooleanField()
#     creator = EmbeddedDocumentField(EmbeddedUser)
#     published_dates = ListField(DateTimeField())
#     tags = ListField(StringField(max_length=30))
#     past_authors = ListField(ReferenceField(User))
#     comments = ListField(EmbeddedDocumentField(Comment))
# 
#     def save(self, *args, **kwargs):
#         if not self.created_date:
#             self.created_date = datetime.utcnow()
#             if not self.creator:
#                 self.creator = EmbeddedUser()
#                 self.creator.email = self.author.email
#                 self.creator.first_name = self.author.first_name
#                 self.creator.last_name = self.author.last_name
#         if self.published:
#             self.published_dates.append(datetime.utcnow())
#         super(Post, self).save(*args, **kwargs)
# 
# class NewUser(User):
#     new_field = StringField()
# 
#     def __unicode__(self):
#         return self.email
# 
# Path: mongonaut/templatetags/mongonaut_tags.py
# @register.simple_tag()
# def get_document_value(document, key):
#     '''
#     Returns the display value of a field for a particular MongoDB document.
#     '''
#     value = getattr(document, key)
#     if isinstance(value, ObjectId):
#         return value
# 
#     if isinstance(document._fields.get(key), URLField):
#         return mark_safe("""<a href="{0}">{1}</a>""".format(value, value))
# 
#     if isinstance(value, Document):
#         app_label = value.__module__.replace(".models", "")
#         document_name = value._class_name
#         url = reverse(
#             "document_detail",
#             kwargs={'app_label': app_label, 'document_name': document_name,
#                     'id': value.id})
#         return mark_safe("""<a href="{0}">{1}</a>""".format(url, value))
# 
#     return value


import unittest
import django
from importlib import import_module
from django.test import RequestFactory
from bson.objectid import ObjectId
from django.core.urlresolvers import NoReverseMatch
from django.conf import settings
from mongonaut.views import DocumentDetailView
from common.utils import DummyUser
from examples.blog.articles.models import Post, NewUser
from mongonaut.templatetags.mongonaut_tags import get_document_value
        try:
            self.view.render()
        except NoReverseMatch as e:
            match_found = False

        settings.ROOT_URLCONF = urls_tmp
        
        self.assertEquals(match_found, True)

    def testUnicodeURLResolver(self):
        '''
            Similarly to testURLResolver, it tests whether get_document_value does not throw an exception.
            This time, the value with unicode characters is provided.
        '''
        
        settings.ROOT_URLCONF = 'examples.blog.urls'

        # Some unicode characters

        email = u"ąćźżńłóśę@gmail.com"

        u = NewUser(email=email)
        u.id=ObjectId('abcabcabcabc')

        p = Post(author=u, title='Test Post')
        p.id = ObjectId('abcabcabcabc')

        unicode_ok = False

        try:

# Path: mongonaut/views.py
# class DocumentDetailView(MongonautViewMixin, TemplateView):
#     """ :args: <app_label> <document_name> <id> """
#     template_name = "mongonaut/document_detail.html"
#     permission = 'has_view_permission'
# 
#     def get_context_data(self, **kwargs):
#         context = super(DocumentDetailView, self).get_context_data(**kwargs)
#         self.set_mongoadmin()
#         context = self.set_permissions_in_context(context)
#         self.document_type = getattr(self.models, self.document_name)
#         self.ident = self.kwargs.get('id')
#         self.document = self.document_type.objects.get(pk=self.ident)
# 
#         context['document'] = self.document
#         context['app_label'] = self.app_label
#         context['document_name'] = self.document_name
#         context['keys'] = ['id', ]
#         context['embedded_documents'] = []
#         context['list_fields'] = []
#         for key in sorted([x for x in self.document._fields.keys() if x != 'id']):
#             # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view
#             # Note - This is the challenge part, right? :)
#             if isinstance(self.document._fields[key], EmbeddedDocumentField):
#                 context['embedded_documents'].append(key)
#                 continue
#             if isinstance(self.document._fields[key], ListField):
#                 context['list_fields'].append(key)
#                 continue
#             context['keys'].append(key)
#         return context
# 
# Path: examples/blog/articles/models.py
# class Post(Document):
#     # See Post.title.max_length to make validation better!
#     title = StringField(max_length=120, required=True, unique=True)
#     content = StringField(default="I am default content")
#     author = ReferenceField(User, required=True)
#     created_date = DateTimeField()
#     published = BooleanField()
#     creator = EmbeddedDocumentField(EmbeddedUser)
#     published_dates = ListField(DateTimeField())
#     tags = ListField(StringField(max_length=30))
#     past_authors = ListField(ReferenceField(User))
#     comments = ListField(EmbeddedDocumentField(Comment))
# 
#     def save(self, *args, **kwargs):
#         if not self.created_date:
#             self.created_date = datetime.utcnow()
#             if not self.creator:
#                 self.creator = EmbeddedUser()
#                 self.creator.email = self.author.email
#                 self.creator.first_name = self.author.first_name
#                 self.creator.last_name = self.author.last_name
#         if self.published:
#             self.published_dates.append(datetime.utcnow())
#         super(Post, self).save(*args, **kwargs)
# 
# class NewUser(User):
#     new_field = StringField()
# 
#     def __unicode__(self):
#         return self.email
# 
# Path: mongonaut/templatetags/mongonaut_tags.py
# @register.simple_tag()
# def get_document_value(document, key):
#     '''
#     Returns the display value of a field for a particular MongoDB document.
#     '''
#     value = getattr(document, key)
#     if isinstance(value, ObjectId):
#         return value
# 
#     if isinstance(document._fields.get(key), URLField):
#         return mark_safe("""<a href="{0}">{1}</a>""".format(value, value))
# 
#     if isinstance(value, Document):
#         app_label = value.__module__.replace(".models", "")
#         document_name = value._class_name
#         url = reverse(
#             "document_detail",
#             kwargs={'app_label': app_label, 'document_name': document_name,
#                     'id': value.id})
#         return mark_safe("""<a href="{0}">{1}</a>""".format(url, value))
# 
#     return value


# Path: tests/url_tests.py
import unittest
import django
from importlib import import_module
from django.test import RequestFactory
from bson.objectid import ObjectId
from django.core.urlresolvers import NoReverseMatch
from django.conf import settings
from mongonaut.views import DocumentDetailView
from common.utils import DummyUser
from examples.blog.articles.models import Post, NewUser
from mongonaut.templatetags.mongonaut_tags import get_document_value

        try:
            self.view.render()
        except NoReverseMatch as e:
            match_found = False

        settings.ROOT_URLCONF = urls_tmp
        
        self.assertEquals(match_found, True)

    def testUnicodeURLResolver(self):
        '''
            Similarly to testURLResolver, it tests whether get_document_value does not throw an exception.
            This time, the value with unicode characters is provided.
        '''
        
        settings.ROOT_URLCONF = 'examples.blog.urls'

        # Some unicode characters

        email = u"ąćźżńłóśę@gmail.com"

        u = NewUser(email=email)
        u.id=ObjectId('abcabcabcabc')

        p = Post(author=u, title='Test Post')
        p.id = ObjectId('abcabcabcabc')

        unicode_ok = False

        try:

            res = get_document_value(p, 'author')