#!/usr/bin/env python

import os
import sys

from redis_rpc_client import RedisRPCClient
from config import Config


class VOSImport(RedisRPCClient):

    def __init__(self):
        config = Config("/etc/vos_cli/vos_cli.conf")
        self.params = config.loadSection("server")
        self.host = self.params["host"]
        self.port = self.params.getint("port")
        self.db = self.params.getint("db")
        self.params = config.loadSection("vos_import")
        self.rpcQueue = self.params["rpc_queue"]
        super(VOSImport, self).__init__(self.host, self.port, self.db, self.rpcQueue)

    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_STARTED":
            print("\nImport procedure started.\nYou'll receive an email at the end of the operation.\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 VOSImport object
vosImportCli = VOSImport()

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

vosImportCli.load(path, username)
