#!/usr/bin/env python
# coding=utf-8

import json
import os
import subprocess
import sys
import tempfile
import time

from pika import BasicProperties
from pika import BlockingConnection
from pika import ConnectionParameters


BERTIE_JAR = "/docker/bertie-uima/target/bertie-uima-0.0.1-SNAPSHOT.jar"


def uima_callback(channel, method, props, body):
    print " [x] Received %r" % (body,)

    def send_response(response):
        print "Sending response..."
        channel.basic_publish(exchange='',
                              routing_key=props.reply_to,
                              properties=BasicProperties(correlation_id=props.correlation_id),
                              body=response)
        channel.basic_ack(delivery_tag=method.delivery_tag)

    # Try decode JSON
    try:
        uima = json.loads(body)
    except ValueError:
        send_response("ERROR")
        return

    function = uima['function']
    text = uima['text']
    lemma = uima['lemma']
    collection_path = uima['collection_path']

    # Dummy elements
    # TODO: annotations should handle emtpy result properly
    placename = u'廬陵'
    persname = u'蘇舜欽'
    term = u'節度使'

    # Check for know functions and assign lemma
    if function == 'persname':
        persname = lemma
    elif function == 'placename':
        placename = lemma
    elif function == 'term':
        term = lemma
    else:
        send_response("ERROR")
        return


    # Build owl
    owl_file = open("/docker/dublin-store/rdf/owl_fragment.rdf")
    owl_fragment = owl_file.read().decode('utf-8')
    owl_fragment = owl_fragment.format(persname=persname, placename=placename, term=term)

    f = tempfile.NamedTemporaryFile(delete=False)
    f.write(owl_fragment.encode('utf-8'))
    f.close()

    # Update repo before change
    os.chdir(collection_path)
    subprocess.call(["ssh-agent", "bash", "-c", "ssh-add /docker/github_rsa ; /usr/bin/git pull;"])

    # Call UIMA analysis engine
    start_uima = time.time()
    result = subprocess.call(["/usr/bin/java", "-Dfile.encoding=UTF-8", "-jar", BERTIE_JAR,
                              "--tei",
                              "--directory", collection_path,
                              "--owl", f.name])
    done_uima = time.time()
    print done_uima - start_uima

    # Remove tempfile
    os.unlink(f.name)

    # Commit the mess
    subprocess.call(["/usr/bin/git", "commit", "-m", "UIMA " + lemma, "."])
    subprocess.call(["ssh-agent", "bash", "-c", "ssh-add /docker/github_rsa ; /usr/bin/git push;"])

    send_response("UIMA")

if __name__ == "__main__":
    #
    # Find rabbitmq server
    #
    try:
        rabbitmq_host = os.environ['RABBITMQ_PORT_5672_TCP_ADDR']
    except KeyError:
        print "Can't find rabbitmq server. Giving up."
        sys.exit(-1)

    connection = BlockingConnection(ConnectionParameters(host=rabbitmq_host))
    channel = connection.channel()
    channel.queue_declare('uima_worker')
    channel.basic_consume(uima_callback, queue='uima_worker')

    print " [x] Awaiting RPC UIMA requests"
    channel.start_consuming()

@@ -765,16 +765,19 @@
   # Try 
+to 
 decode J
@@ -779,16 +779,24 @@
 ode JSON
+ payload
 %0A    try
@@ -837,74 +837,8 @@
     
-except ValueError:%0A        send_response(%22ERROR%22)%0A        return%0A%0A
     
@@ -865,16 +865,20 @@
 ction'%5D%0A
+    
     text
@@ -897,16 +897,20 @@
 t'%5D%0A    
+  
+  
 lemma = 
@@ -923,16 +923,20 @@
 lemma'%5D%0A
+    
     coll
@@ -972,16 +972,128 @@
 n_path'%5D
+%0A        juan = int(uima%5B'juan'%5D)%0A    except ValueError, KeyError:%0A        send_response(%22ERROR%22)%0A        return
 %0A%0A    # 
@@ -2035,104 +2035,807 @@
     
-start_uima = time.time()%0A    result = subprocess.call(%5B%22/usr/bin/java%22, %22-Dfile.encoding=UTF-8%22,
+if not juan == -1:%0A        file_name = %22/%2503d.xml%22 %25 (juan,)%0A        result = subprocess.call(%5B%22/usr/bin/java%22, %22-Dfile.encoding=UTF-8%22,%0A                                  %22-Djava.util.logging.config.file=/docker/bertie-uima/src/main/properties/Logger.properties%22,%0A                                  %22-jar%22, BERTIE_JAR,%0A                                  %22--tei%22,%0A                                  %22--file%22, collection_path + file_name,%0A                                  %22--owl%22, f.name%5D)%0A%0A        # Send response early%0A        send_response(%22OK%22)%0A%0A    start_uima = time.time()%0A    result = subprocess.call(%5B%22/usr/bin/java%22, %22-Dfile.encoding=UTF-8%22,%0A                              %22-Djava.util.logging.config.file=/docker/bertie-uima/src/main/properties/Logger.properties%22,%0A                             
  %22-j
@@ -3024,24 +3024,44 @@
 time.time()%0A
+    print %22RUNTIME%22%0A
     print do
@@ -3082,16 +3082,121 @@
 t_uima%0A%0A
+    # No single juan was annotated, so send response now%0A    if juan == -1:%0A        send_repsonse(%22OK%22)%0A%0A
     # Re
@@ -3435,35 +3435,8 @@
 %5D)%0A%0A
-    send_response(%22UIMA%22)%0A%0A
 if _
@@ -3648,16 +3648,72 @@
 ng up.%22%0A
+        print %22Please set RABBITMQ_PORT_5672_TCP_ADDR.%22%0A
         

Support annotation of single juan