# Path: flat/views.py
# def initdoc(request, namespace, docid, mode, template, context=None, configuration=None):
#     """Initialise a document (not invoked directly)"""
#     perspective = request.GET.get('perspective','document')
#     if context is None: context = {}
#     if configuration is None:
#         if 'configuration' in request.session:
#             configuration = request.session['configuration']
#         else:
#             return fatalerror(request, "No configuration specified")
#     if configuration not in settings.CONFIGURATIONS:
#         return fatalerror(request, "Specified configuration does not exist")
#     flatargs = {
#         'setdefinitions': True,
#         'declarations': True, #implies provenance as well
#         'metadata': True,
#         'toc': True,
#         'slices': request.GET.get('slices',settings.CONFIGURATIONS[configuration].get('slices','p:25,s:100')), #overriden either by configuration or by user
#         'customslicesize': 0, #disabled for initial probe
#         'textclasses': True,
#     }
#     error = False
#     try:
#         doc = flat.comm.query(request, "USE " + namespace + "/" + docid + " PROBE", **flatargs) #retrieves only the meta information, not document content
#         context.update(getcontext(request,namespace,docid, doc, mode, configuration))
#     except Exception as e:
#         context.update(docserveerror(e))
#         error = True
# 
#     if not error:
#         dorequiredeclaration = 'requiredeclaration' in settings.CONFIGURATIONS[configuration] and settings.CONFIGURATIONS[configuration]['requiredeclaration']
#         if dorequiredeclaration:
#             if not 'declarations' in doc:
#                 return fatalerror(request, "Refusing to load document, missing expected declarations, none declared")
#             declarations = doc['declarations']
#             for annotationtype, annotationset in settings.CONFIGURATIONS[configuration]['requiredeclaration']:
#                 found = False
#                 for d in declarations:
#                     if annotationtype == d['annotationtype'] and (not annotationset or annotationset == d['set']):
#                         found = True
#                         break
#                 if not found:
#                     if annotationset:
#                         return fatalerror(request, "Refusing to load document, missing expected declaration for annotation type " + annotationtype + "/" + annotationset)
#                     else:
#                         return fatalerror(request, "Refusing to load document, missing expected declaration for annotation type " + annotationtype)
# 
#         dometadataindex = 'metadataindex' in settings.CONFIGURATIONS[configuration] and settings.CONFIGURATIONS[configuration]['metadataindex']
#         if dometadataindex:
#             metadata = json.loads(context['metadata'])
#             for metakey in settings.CONFIGURATIONS[configuration]['metadataindex']:
#                 if metakey in metadata:
#                     MetadataIndex.objects.update_or_create(namespace=namespace,docid=docid, key=metakey,defaults={'value':metadata[metakey]})
#     response = render(request, template, context)
#     if 'fatalerror' in context:
#         response.status_code = 500
#     return response
# 
# @login_required
# def query(request,namespace, docid):
#     if request.method != 'POST':
#         return HttpResponseForbidden("POST method required for " + namespace + "/" + docid + "/query")
# 
#     if flat.users.models.hasreadpermission(getusername(request), namespace, request):
#         return query_helper(request, namespace,docid, request.session['configuration'])
#     else:
#         return HttpResponseForbidden("Permission denied, no read access")
# 
# def getusername(request):
#     if hasattr(settings, 'OIDC') and settings.OIDC:
#         return request.user.email
#     return request.user.username


from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from flat.views import initdoc, query, getusername
from urllib.error import URLError
import flat.comm
import flat.users
import json
import sys
from __future__ import print_function, unicode_literals, division, absolute_import



@login_required
def view(request, namespace, docid):
    """The initial viewer, does not provide the document content yet"""
    return initdoc(request, namespace,docid, 'viewer', 'viewer.html')

@login_required
def poll(request, namespace, docid):
    if flat.users.models.hasreadpermission(getusername(request), namespace, request):
        try:
            r = flat.comm.get(request, '/poll/' + namespace + '/' + docid + '/', False)
        except URLError:
            return HttpResponseForbidden("Unable to connect to the document server [viewer/poll]")
        return HttpResponse(r, content_type='application/json')
    else:
        return HttpResponseForbidden("Permission denied")

@csrf_exempt
def pub_view(request, configuration, docid):
    """The initial viewer, does not provide the document content yet"""

# Path: flat/views.py
# def initdoc(request, namespace, docid, mode, template, context=None, configuration=None):
#     """Initialise a document (not invoked directly)"""
#     perspective = request.GET.get('perspective','document')
#     if context is None: context = {}
#     if configuration is None:
#         if 'configuration' in request.session:
#             configuration = request.session['configuration']
#         else:
#             return fatalerror(request, "No configuration specified")
#     if configuration not in settings.CONFIGURATIONS:
#         return fatalerror(request, "Specified configuration does not exist")
#     flatargs = {
#         'setdefinitions': True,
#         'declarations': True, #implies provenance as well
#         'metadata': True,
#         'toc': True,
#         'slices': request.GET.get('slices',settings.CONFIGURATIONS[configuration].get('slices','p:25,s:100')), #overriden either by configuration or by user
#         'customslicesize': 0, #disabled for initial probe
#         'textclasses': True,
#     }
#     error = False
#     try:
#         doc = flat.comm.query(request, "USE " + namespace + "/" + docid + " PROBE", **flatargs) #retrieves only the meta information, not document content
#         context.update(getcontext(request,namespace,docid, doc, mode, configuration))
#     except Exception as e:
#         context.update(docserveerror(e))
#         error = True
# 
#     if not error:
#         dorequiredeclaration = 'requiredeclaration' in settings.CONFIGURATIONS[configuration] and settings.CONFIGURATIONS[configuration]['requiredeclaration']
#         if dorequiredeclaration:
#             if not 'declarations' in doc:
#                 return fatalerror(request, "Refusing to load document, missing expected declarations, none declared")
#             declarations = doc['declarations']
#             for annotationtype, annotationset in settings.CONFIGURATIONS[configuration]['requiredeclaration']:
#                 found = False
#                 for d in declarations:
#                     if annotationtype == d['annotationtype'] and (not annotationset or annotationset == d['set']):
#                         found = True
#                         break
#                 if not found:
#                     if annotationset:
#                         return fatalerror(request, "Refusing to load document, missing expected declaration for annotation type " + annotationtype + "/" + annotationset)
#                     else:
#                         return fatalerror(request, "Refusing to load document, missing expected declaration for annotation type " + annotationtype)
# 
#         dometadataindex = 'metadataindex' in settings.CONFIGURATIONS[configuration] and settings.CONFIGURATIONS[configuration]['metadataindex']
#         if dometadataindex:
#             metadata = json.loads(context['metadata'])
#             for metakey in settings.CONFIGURATIONS[configuration]['metadataindex']:
#                 if metakey in metadata:
#                     MetadataIndex.objects.update_or_create(namespace=namespace,docid=docid, key=metakey,defaults={'value':metadata[metakey]})
#     response = render(request, template, context)
#     if 'fatalerror' in context:
#         response.status_code = 500
#     return response
# 
# @login_required
# def query(request,namespace, docid):
#     if request.method != 'POST':
#         return HttpResponseForbidden("POST method required for " + namespace + "/" + docid + "/query")
# 
#     if flat.users.models.hasreadpermission(getusername(request), namespace, request):
#         return query_helper(request, namespace,docid, request.session['configuration'])
#     else:
#         return HttpResponseForbidden("Permission denied, no read access")
# 
# def getusername(request):
#     if hasattr(settings, 'OIDC') and settings.OIDC:
#         return request.user.email
#     return request.user.username


# Path: flat/modes/viewer/views.py
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from flat.views import initdoc, query, getusername
from urllib.error import URLError
import flat.comm
import flat.users
import json
import sys

from __future__ import print_function, unicode_literals, division, absolute_import



@login_required
def view(request, namespace, docid):
    """The initial viewer, does not provide the document content yet"""
    return initdoc(request, namespace,docid, 'viewer', 'viewer.html')

@login_required
def poll(request, namespace, docid):
    if flat.users.models.hasreadpermission(getusername(request), namespace, request):
        try:
            r = flat.comm.get(request, '/poll/' + namespace + '/' + docid + '/', False)
        except URLError:
            return HttpResponseForbidden("Unable to connect to the document server [viewer/poll]")
        return HttpResponse(r, content_type='application/json')
    else:
        return HttpResponseForbidden("Permission denied")

@csrf_exempt
def pub_view(request, configuration, docid):
    """The initial viewer, does not provide the document content yet"""

    return initdoc(request, 'pub',docid, 'viewer', 'viewer.html', configuration=configuration)