'''The client side of the multi_facility_process_helper.
Mostly a utility class with a lot of convenience methods.'''
import sys
import os.path
import json
import subprocess
import globals
import toolconfig


def executeCommandsOnFacility(facility, commandsAndArgs):
    '''Executes a list of commands on the specified facility using ssh and the multi_facility_process_helper. 
    facility - This is the facility name.
    commandsAndArgs - A list of tuples - each tuple has two components. First component is a string command. Second command is a jsonable arg. Both are mandatory.
    We return the deserialized contents of executing the set of commands on the remote facility as a list of objects
    '''
    facilityConfig = toolconfig.getConfigForFacility(facility)
    # Each facility has a config element that tells us machine and use credentials. 
    ssh = facilityConfig['ssh']
    try:
        proc = subprocess.Popen(['ssh', globals.dmzmachine, 'ssh ', ssh, 'multi_facility_process_helper.py'],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
        commandStr = json.dumps(commandsAndArgs)
        if globals.verbose:
            print "Sending to remote multi_facility_process_helper - ", commandStr, "on", facility, "with ssh =", ssh, " using dmzmachine", globals.dmzmachine
        [stdoutdata, stderrdata] = proc.communicate(commandStr)
        if globals.verbose:
            print "stderr", stderrdata
        if globals.verbose:
            print "stdout", stdoutdata
        ret = json.loads(stdoutdata)
        if globals.verbose:
            print "Return from multi_facility_process_helper", ret
        return ret
    except subprocess.CalledProcessError:
        return ""
