#!/usr/bin/env python

###############################################################################
# (c) Copyright 2018 CERN                                                     #
#                                                                             #
# This software is distributed under the terms of the GNU General Public      #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING".   #
#                                                                             #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization  #
# or submit itself to any jurisdiction.                                       #
###############################################################################
'''
Command line client that interfaces to the Installer class

:author: Stefan-Gabriel CHITIC
'''
from __future__ import print_function
import logging
import optparse
import os
import re
import sys
import traceback
import shutil

from os.path import abspath

from LbSoftConfDb2Server.Neo4jEnvSetup import Neo4jEnvSetup

# Class for known install exceptions
###############################################################################


class Neo4jSetupException(Exception):
    """ Custom exception for lb-install

    :param msg: the exception message
    """

    def __init__(self, msg):
        """ Constructor for the exception """
        # super(Neo4jSetupException, self).__init__(msg)
        Exception.__init__(self, msg)


# Classes and method for command line parsing
###############################################################################


class Neo4jSetupOptionParser(optparse.OptionParser):
    """ Custom OptionParser to intercept the errors and rethrow
    them as Neo4jSetupExceptions """

    def error(self, msg):
        """
        Arguments parsing error message exception handler

        :param msg: the message of the exception
        :return: Raises Neo4jSetupException with the exception message
        """
        raise Neo4jSetupException("Error parsing arguments: " + str(msg))

    def exit(self, status=0, msg=None):
        """
        Arguments parsing error message exception handler

        :param status: the status of the application
        :param msg: the message of the exception
        :return: Raises Neo4jSetupException with the exception message
        """
        raise Neo4jSetupException("Error parsing arguments: " + str(msg))


class Neo4jSetupClient(object):
    """ Main class for the tool """

    def __init__(self, configType, arguments=None, prog="lb-load-neo4j-env"):
        """ Common setup for both clients """
        self.configType = configType
        self.log = logging.getLogger(__name__)
        self.arguments = arguments
        self.db_path = None
        self.port = None
        parser = Neo4jSetupOptionParser(usage=usage(prog))
        # parser.disable_interspersed_args()

        parser.add_option('--db_path',
                          dest="db_path",
                          default='graph.db',
                          action="store",
                          help="Specify path for the database")
        parser.add_option('--port',
                          dest="port",
                          default='7687',
                          action="store",
                          help="Specify specific port")
        self.parser = parser

    def main(self):
        """ Main method for the ancestor:
        call parse and run in sequence

        :returns: the return code of the call
        """
        rc = 0
        try:
            opts, args = self.parser.parse_args(self.arguments)

            if opts.db_path:
                self.db_path = opts.db_path
            if opts.port:
                self.port = opts.port
            self.run(opts, args)

        except Neo4jSetupException as lie:
            print("ERROR: " + str(lie), file=sys.stderr)
            self.parser.print_help()
            rc = 1
        except Exception as _:
            print("Exception in lb-install:", file=sys.stderr)
            print('-'*60, file=sys.stderr)
            traceback.print_exc(file=sys.stderr)
            print('-'*60, file=sys.stderr)
            rc = 1
        return rc

    def run(self, opts, args):
        """ Main method for the command

        :param opts: The option list
        :param args: The arguments list
        """
        # Parsing first argument to check the mode
        if len(args) != 1:
            raise Neo4jSetupException("Neo4j path should be specify")
        setup = Neo4jEnvSetup(args[0], db_path=self.db_path, port=self.port)
        setup.start()


# Usage for the script
###############################################################################
def usage(cmd):
    """ Prints out how to use the script...

    :param cmd: the command executed
    """
    cmd = os.path.basename(cmd)
    return """\n%(cmd)s -  setups the environment for local neo4j server'
%(cmd)s <neo4j-installation-path>

""" % {"cmd": cmd}


def Neo4jSetup(configType="LHCbConfig", prog="Neo4jSetup"):
    """
    Default caller for command line Neo4jSetup client
    :param configType: the configuration used
    :param prog: the name of the executable
    """
    logging.basicConfig(format="%(levelname)-8s: %(message)s")
    logging.getLogger().setLevel(logging.INFO)
    sys.exit(Neo4jSetupClient(configType, prog=prog).main())

# Main just chooses the client and starts it
if __name__ == "__main__":
    Neo4jSetup()
