from fabric.state import env
from fabric.operations import run, put


class SearchEngineLoader(object):

    class OperationError(Exception):
        pass

    def __init__(self, host, username, key):
        """
        Created an instance of this object
        @param host: IP address of host of server to connect
        @type host: str
        @param username: Username used to connect
        @type username: str
        @param key: Path to the ssh key used for authentication
        @type key: str
        """
        super(SearchEngineLoader, self).__init__()
        env.host_string = host
        env.user = username
        env.key_filename = key

        # Dont' exit app when there is an error
        def raise_error(msg):
            raise self.OperationError(msg)

        env.abort_exception = lambda msg: raise_error(msg)

    def load_xmlgen(self, xmlfile, logger):
        """
        Loads a xmlgen file to the server and starts a re-index of the search engine
        @param xmlfile: XML text to load on the search engine
        @type xmlfile: str
        """
        try:
            env.shell_env = {"PROJECT_DIR": '/mnt/solr/indexer',
                             "DATA_DIR": "/mnt/solr/datafeed"}

            # Upload xmlgen file
            logger.debug("Uploading file %s" % xmlfile)
            put(xmlfile,
                r"/mnt/solr/datafeed/MainSystem/ypse.ypca.140218.2252.0.xml")

            #Start re-index
            logger.debug("Start re-index of search engine")
            run('${PROJECT_DIR}/bin/execute_merchant.sh ${PROJECT_DIR} ${DATA_DIR}', shell=True)
        except Exception as e:
            logger.error("Error uploading xmlgen file:\\n%s" % e.message)
            raise e

