
from django.shortcuts import render
from django.template.loader import render_to_string
from django.template import RequestContext
from datetime import datetime

from ..base.models import Request

import app_settings


def list_records(request, context):
    """ ListRecords implementation
    """
    if not request.GET.has_key('metadataPrefix'):
        return render(request, 'oai/bad_argument.xml', context, content_type='text/xml')
    metadata = request.GET['metadataPrefix']
    if metadata != 'oai_dc':
        return render(request, 'oai/cannot_disseminate_format.xml', context, content_type='text/xml')

    records = ''
    for i, polynum_request in enumerate(Request.objects.all()):
        records += render_to_string('oai/record.xml',
                {'prequest': polynum_request, 
                'etablissement': 'Dauphine',
                'datetime': datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
                'hostname': request.get_host(),
                'i': i
                })
    context = RequestContext(request,
            {
            'datetime': datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
            'url': request.build_absolute_uri(request.path),
            'records': records,
            })
    return render(request, 'oai/list_records.xml', context, content_type='text/xml')


def request(request):
    context = RequestContext(request,
            {
            'datetime': datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
            'url': request.build_absolute_uri(request.path),
            'hostname': request.get_host(),
            'settings': app_settings
            })
    if request.GET.has_key('verb'):
        if request.GET['verb'] == 'Identify':
            return render(request, 'oai/identify.xml', context, content_type='text/xml')
        elif request.GET['verb'] == 'ListMetadataFormats':
            return render(request, 'oai/list_metadata_formats.xml', context, content_type='text/xml')
        elif request.GET['verb'] == 'ListRecords':
            return list_records(request, context)
    return render(request, 'oai/bad_verb.xml', context, content_type='text/xml')

