#!/usr/bin/env python

"""
Step 5
======
In this step, we'll create a new history named 'Step 5' and upload a file
to it to create a new HDA.
"""
import os
import sys
import pprint

import users_1
import histories_3
# note: that we're using the new tools module for this step
import tools_1
# and we're using the new get_hda from hdas_2
import hdas_2

NEW_HISTORY_NAME = 'Step 5'
# we'll now store the name of the file to upload here
DATA_TO_UPLOAD = 'data/myIlluminaRun.solexa.fastq'

# ----------------------------------------------------------------------------- main
if __name__ == '__main__':
    try:
        # check the connection
        users = users_1.get_users()

        # create a new history
        new_history = histories_3.create_history( NEW_HISTORY_NAME )
        print 'created history!', new_history[ 'name' ]
        new_history_id = new_history[ 'id' ]
        new_history_details = histories_3.get_history( new_history_id )

        # upload a file - the tool API will generally return a list of 'outputs' when
        #   running a tool. Since we know there will only be one output from the upload tool, grab it
        tool_output_datasets = tools_1.upload_hda( new_history_id, DATA_TO_UPLOAD )
        # outputs is a list of dictionaries
        uploaded_file_data = tool_output_datasets[ 'outputs' ][0]
        print 'uploaded hda!', uploaded_file_data[ 'name' ]
        uploaded_file_id = uploaded_file_data[ 'id' ]

        # get the (not empty!) list of hdas inside that history
        hdas = hdas_2.get_hdas( new_history_id )
        # and use get_hda to get details on the new, uploaded HDA
        uploaded_hda_details = hdas_2.get_hda( new_history_id, uploaded_file_id )
        
    except Exception, exc:
        print 'Error uploading file to history:', str( exc )
        sys.exit( 1 )

    print 'HDAs now:'
    pprint.pprint( hdas, indent=2 )
    print 'Uploaded:'
    pprint.pprint( uploaded_hda_details, indent=2 )
