import logging
import os

from dirq.queue import Queue
from django.conf import settings
from rest_framework.response import Response
from rest_framework.views import APIView


class IndexView(APIView):
    """An example URL."""

    def get(self, request, format=None):
        """An example get method."""
        logger = logging.getLogger(__name__)

        response = "Hello, world. You're at the index."
        logger.info(response)
        return Response(response, status=200)

    def post(self, request, format=None):
        """An example post method."""
        logger = logging.getLogger(__name__)

        try:
            empaid = request.META['HTTP_EMPA_ID']
        except KeyError:
            empaid = 'noid'

        logger.info("Received message. ID = %s", empaid)

        # this will fail is the request isn't coming through apache
        signer = request.META['SSL_CLIENT_S_DN']

        if "_content" in request.POST.dict():
            # then POST likely to come via the rest api framework
            # hence use the content of request.POST as message
            body = request.POST.get('_content')
        else:
            # POST likely to comes through a browser client or curl
            # hence use request.body as message
            body = request.body

        logger.debug("Message body received: %s", body)

        for header in request.META:
            logger.debug("%s: %s", header, request.META[header])

        # taken from ssm2
        QSCHEMA = {'body': 'string',
                   'signer': 'string',
                   'empaid': 'string?'}

        inqpath = os.path.join(settings.QPATH, 'incoming')
        # rejectqpath = os.path.join(qpath, 'reject')
        inq = Queue(inqpath, schema=QSCHEMA)
        # rejectq = Queue(rejectqpath, schema=REJECT_SCHEMA)

        name = inq.add({'body': body,
                        'signer': signer,
                        'empaid': empaid})

        logger.info("Message saved to in queue as %s/%s", inqpath, name)
        response = "Data received is well-formed and stored for processing."
        return Response(response, status=202)

@@ -47,16 +47,28 @@
 rt Queue
+, QueueError
 %0Afrom dj
@@ -180,16 +180,67 @@
 PIView%0A%0A
+from apel.db.loader import Loader, LoaderException%0A
 %0Aclass I
@@ -855,116 +855,118 @@
     
-# this will fail is the request isn't coming through apache%0A        signer = request.META%5B'SSL_CLIENT_S_DN'%5D
+try:%0A            signer = request.META%5B'SSL_CLIENT_S_DN'%5D%0A        except KeyError:%0A            signer = %22None%22
 %0A%0A  
@@ -1871,16 +1871,33 @@
 CHEMA)%0A%0A
+        try:%0A    
         
@@ -1942,32 +1942,36 @@
                 
+    
 'signer': signer
@@ -1972,16 +1972,20 @@
 signer,%0A
+    
         
@@ -2018,16 +2018,250 @@
 empaid%7D)
+%0A        except QueueError as err:%0A            logger.error(%22Could not save %25s/%25s: %25s%22, inqpath, name, err)%0A%0A            response = %22Data could not be saved to disk, please try again.%22%0A            return Response(response, status=500)
 %0A%0A      
@@ -2327,24 +2327,25 @@
 , name)%0A
+%0A
         
 response
@@ -2340,74 +2340,853 @@
     
-response = %22Data received is well-formed and stored for processing
+try: # and load messages into database%0A            loader = Loader(settings.QPATH,%0A                            True,  # backend%0A                            'mysql',  # save messages%0A                            'localhost',  # hostname%0A                            3306,  # port%0A                            'apel_rest',  # name%0A                            'root',  # username%0A                            '',  # password%0A                            '/var/run/apel/loader.pid')  # pidfile%0A%0A            loader.startup()%0A            loader.load_all_msgs()%0A            loader.shutdown()%0A        except LoaderException as err:%0A            logger.error(%22Loader exception occured: %25s%22, err)%0A%0A            response = %22Data could not be stored, please try again%22%0A            return Response(response, status=500)%0A%0A        response = %22Data successfully loaded
 .%22%0A 
@@ -3227,11 +3227,11 @@
 tatus=20
-2
+0
 )%0A

Load messages into database before returning 200