#!/usr/bin/env python

"""
Access a Galaxy instance and get data for Workflows.

Creating three functions at once in this file.
"""
import os
import sys
import pprint

import setup
import common

RESOURCE_URL = '/api/workflows'

# adding things quickly now - three functions at once

# ----------------------------------------------------------------------------- functions
def get_workflows():
    """
    Return a list of dictionaries of summary information for all workflows.
    """
    apikey = setup.get_apikey()
    full_url = setup.get_base_url() + RESOURCE_URL
    return common.get( apikey, full_url )

def get_workflow( workflow_id ):
    """
    Return a dictionary of detailed information for a specific workflow.
    :param workflow_id: the encoded id of the workflow
    """
    apikey = setup.get_apikey()
    full_url = setup.get_base_url() + RESOURCE_URL + '/' + workflow_id
    return common.get( apikey, full_url )

def run_single_input_workflow_on_hda( workflow_id, history_id, hda_id, source_step ):
    """
    Run a workflow that only needs one input using an hda. The outputs
    from the workflow will be kept in the history with `history_id`.

    Some of the options of this part of the API were not included here to
    improve simplicity.

    :param workflow_id: the encoded id of the workflow to run
    :param history_id: the id of the history for input/output
    :param hda_id: the id of the HDA to use as the workflow input
    :param source_step: the id of the initial, input workflow step
    """
    apikey = setup.get_apikey()
    full_url = setup.get_base_url() + RESOURCE_URL

    # a bit complex here...
    # build these first since they need to be contained in the following structures
    step = {
        'src'   : 'hda',
        'id'    : hda_id
    }
    ds_map = {}
    ds_map[ source_step ] = step
    post_data = {
        'workflow_id'   : workflow_id,
        'history'       : 'hist_id=' + history_id,
        'ds_map'        : ds_map
    }
    # above is an example of building complex input arguments for an API call
    #   The documentation for each API function and resource should help in creating these.
    return common.post( apikey, full_url, post_data )


# ----------------------------------------------------------------------------- main
if __name__ == '__main__':
    # we can make this script do double duty by changing functions based on the number of args passed in:
    if   len( sys.argv ) <= 1:
        # no args: get all workflows
        returned = get_workflows()
        pprint.pprint( returned, indent=2 )

    elif len( sys.argv ) <= 2:
        # 1 arg: get a specific workflow
        #NOTE: it's good practice to provide usage/help - in this case we could check if the arg was '-h' and do that
        workflow_id = sys.argv[1]
        returned = get_workflow( workflow_id )
        pprint.pprint( returned, indent=2 )

    # we won't test run_single_input_workflow_on_hda in this script
