import argparse
import sys
from ..pushworkflow.scheme.parser import scheme_load
import logging
try:
    import h5py
    has_h5py = True
except:
    has_h5py = False

logging.basicConfig(level=logging.DEBUG)
_logger = logging.getLogger(__name__)


def exec_(scheme, input_=None, output_=None):
    def manage_input():
        if input_:
            # monkey patch the input file for start nodes if an input is given
            for node in scheme.nodes:
                if node.properties and '_input_file_setting' in node.properties:
                    node.properties['_input_file_setting'] = input_
    manage_input()

    def manage_output():
        if output_:
            # monkey patch the input file for start nodes if an input is given
            for node in scheme.nodes:
                if node.properties and '_output_file_setting' in node.properties:
                    node.properties['_output_file_setting'] = output_

    # TODO: if the input file contains configuration, then overwrite the node
    # properties...
    manage_output()

    if len(scheme._start_actor.listDownStreamActor) is 0:
        _logger.warning('no downstream node defined')
        return None
    scheme._start_actor.trigger(input_)
    scheme._end_actor.join()
    return scheme._end_actor.outData


def getinputinfo():
    return "xas process workflow_file_desc.ows [input]"


def getInputFrmHdf5(file_path):
    raise NotImplementedError()


def main(argv):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        'workflow_file',
        help='Workflow file providing the workflow description (.ows, .xml)')
    parser.add_argument("-i", dest="input_", default=None,
                        help="Input of the workflow. require at most one "
                             "instance of XASInputOW")
    parser.add_argument("-o", dest="output_", default=None,
                        help="Output file of the workflow. Require at most one "
                             "instance of XASOutputOW")
    options = parser.parse_args(argv[1:])

    scheme = scheme_load(_file=options.workflow_file)
    exec_(scheme, options.input_, options.output_)

if __name__ == "__main__":
    main(sys.argv)
