#!/usr/bin/env python

import pika
import uuid
import json
import os
import sys


class AMQPClient(object):

    def __init__(self):
        self.rpcQueue = "import_queue"
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host = "rabbitmq"))
        self.channel = self.connection.channel()
        result = self.channel.queue_declare(queue = '', exclusive = True)
        self.callback_queue = result.method.queue
        self.channel.basic_consume(queue = self.callback_queue, on_message_callback = self.on_response, auto_ack = True)

    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id:
            self.response = json.loads(body)

    def call(self, msg):
        self.response = None
        self.corr_id = str(uuid.uuid4())
        self.channel.basic_publish(exchange = '',
                                   routing_key = self.rpcQueue,
                                   properties = pika.BasicProperties(reply_to = self.callback_queue,
                                                                     correlation_id = self.corr_id,
                                                                    ),
                                   body = json.dumps(msg))

        while self.response is None:
            self.connection.process_data_events()
        return self.response

    def load(self, path, username):
        importRequest = { "requestType": "NODE_IMPORT", "path": path, "userName": username }
        importResponse = self.call(importRequest)
        if "responseType" not in importResponse:
            sys.exit("FATAL: Malformed response, storage acknowledge expected.\n")
        elif importResponse["responseType"] == "IMPORT_DONE":
            print("\nImport procedure completed!\n")
        elif importResponse["responseType"] == "ERROR":
            errorCode = importResponse["errorCode"]
            errorMsg = importResponse["errorMsg"]
            sys.exit(f"\nError code: {errorCode}\nError message: {errorMsg}\n")
        else:
            sys.exit("\nFATAL: Unknown response type.\n")

    def help(self):
        sys.exit("""
NAME
       vos_import

SYNOPSYS
       vos_import DIR_PATH USERNAME

DESCRIPTION
       This tool recursively imports nodes on the VOSpace file catalog.
       
       Two parameters are required:

       DIR_PATH:
           the physical absolute path of a directory located within the 
           user directory for a given mount point.
           
       USERNAME:
           the username used for accessing the transfer node.
           
EXAMPLE
      The following command will import recursively all the nodes contained
      in 'mydir' on the VOSpace for the 'jsmith' user:
      
      # vos_import /mnt/storage/users/jsmith/mydir jsmith   
    """)

# Create new AMQPClient object
vosImportCli = AMQPClient()

# Check the number of input args
if len(sys.argv) == 3:
    script, path, username = sys.argv
else:
    vosImportCli.help()

vosImportCli.load(path, username)
