# Path: api/webview/views.py
# class DocumentList(generics.ListAPIView):
#     """
#     List all documents in the SHARE API
#     """
#     serializer_class = DocumentSerializer
#     permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
# 
#     def perform_create(self, serializer):
#         serializer.save(source=self.request.user)
# 
#     def get_queryset(self):
#         """ Return all documents
#         """
#         # return Document.objects.all().order_by('providerUpdatedDateTime').exclude(normalized=None)
#         return Document.objects.all().exclude(normalized=None)
# 
# @api_view(['GET'])
# @xframe_options_exempt
# def status(request):
#     """
#     Show the status of the API
#     """
#     return HttpResponse(json.dumps({'status': 'ok'}), content_type='application/json', status=200)
# 
# @api_view(['GET', 'POST'])
# def institutions(request):
#     if not es:
#         return HttpResponse('No connection to elastic search', status=503)
#     if request.data.get('query') or request.query_params.get('q'):
#         query = request.data.get('query') or {
#             'query': {
#                 'query_string': {
#                     'query': request.query_params.get('q')
#                 }
#             }
#         }
#     else:
#         query = {
#             'query': {
#                 'match_all': {}
#             }
#         }
# 
#     es.indices.create(index='institutions', ignore=400)
#     res = es.search(index=settings.ELASTIC_INST_INDEX, body=query)
#     # validate query and grab whats wanted
#     try:
#         res = {
#             'results': [val['_source'] for val in res['hits']['hits']],
#             'aggregations': res.get('aggregations') or res.get('aggs'),
#             'count': res['hits']['total']
#         }
#     except IndexError:
#         return Response('Invalid query', status=400)
#     return Response(res, status=200)
# 
# Path: api/webview/models.py
# class Document(models.Model):
#     key = models.TextField(primary_key=True)
#     source = models.CharField(max_length=255)
#     docID = models.TextField()
# 
#     providerUpdatedDateTime = models.DateTimeField(null=True)
# 
#     raw = JsonField()
#     timestamps = JsonField(null=True)
#     normalized = JsonField(null=True)
#     status = models.TextField(null=True)
# 
#     def save(self, *args, **kwargs):
#         if not self.key:
#             self.key = self._make_key(self.source, self.docID)
#         return super(Document, self).save(*args, **kwargs)
# 
#     @classmethod
#     def _make_key(cls, source, docID):
#         return '|'.join((source, docID))


import os
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList, status, institutions
from api.webview.models import Document



django.setup()


class APIViewTests(TestCase):

    def setUp(self):
        self.factory = APIRequestFactory()

    def test_document_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_source_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/dudley_weekly/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_individual_view(self):

# Path: api/webview/views.py
# class DocumentList(generics.ListAPIView):
#     """
#     List all documents in the SHARE API
#     """
#     serializer_class = DocumentSerializer
#     permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
# 
#     def perform_create(self, serializer):
#         serializer.save(source=self.request.user)
# 
#     def get_queryset(self):
#         """ Return all documents
#         """
#         # return Document.objects.all().order_by('providerUpdatedDateTime').exclude(normalized=None)
#         return Document.objects.all().exclude(normalized=None)
# 
# @api_view(['GET'])
# @xframe_options_exempt
# def status(request):
#     """
#     Show the status of the API
#     """
#     return HttpResponse(json.dumps({'status': 'ok'}), content_type='application/json', status=200)
# 
# @api_view(['GET', 'POST'])
# def institutions(request):
#     if not es:
#         return HttpResponse('No connection to elastic search', status=503)
#     if request.data.get('query') or request.query_params.get('q'):
#         query = request.data.get('query') or {
#             'query': {
#                 'query_string': {
#                     'query': request.query_params.get('q')
#                 }
#             }
#         }
#     else:
#         query = {
#             'query': {
#                 'match_all': {}
#             }
#         }
# 
#     es.indices.create(index='institutions', ignore=400)
#     res = es.search(index=settings.ELASTIC_INST_INDEX, body=query)
#     # validate query and grab whats wanted
#     try:
#         res = {
#             'results': [val['_source'] for val in res['hits']['hits']],
#             'aggregations': res.get('aggregations') or res.get('aggs'),
#             'count': res['hits']['total']
#         }
#     except IndexError:
#         return Response('Invalid query', status=400)
#     return Response(res, status=200)
# 
# Path: api/webview/models.py
# class Document(models.Model):
#     key = models.TextField(primary_key=True)
#     source = models.CharField(max_length=255)
#     docID = models.TextField()
# 
#     providerUpdatedDateTime = models.DateTimeField(null=True)
# 
#     raw = JsonField()
#     timestamps = JsonField(null=True)
#     normalized = JsonField(null=True)
#     status = models.TextField(null=True)
# 
#     def save(self, *args, **kwargs):
#         if not self.key:
#             self.key = self._make_key(self.source, self.docID)
#         return super(Document, self).save(*args, **kwargs)
# 
#     @classmethod
#     def _make_key(cls, source, docID):
#         return '|'.join((source, docID))


# Path: tests/test_api_views.py
import os
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList, status, institutions
from api.webview.models import Document




django.setup()


class APIViewTests(TestCase):

    def setUp(self):
        self.factory = APIRequestFactory()

    def test_document_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_source_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/dudley_weekly/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_individual_view(self):

        view = DocumentList.as_view()