#!/usr/bin/env python

"""
Step 6
======
In this step, we'll create a new history named 'Step 6', upload a file
to it to create a new HDA, and wait for that HDA to move into the 'ok' state.
"""
import os
import sys
import pprint
# we'll use the python library time to get a function called sleep
import time

import users_1
import histories_3
import tools_1
import hdas_2

NEW_HISTORY_NAME = 'Step 6'
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
        tool_output_datasets = tools_1.upload_hda( new_history_id, DATA_TO_UPLOAD )
        uploaded_file_data = tool_output_datasets[ 'outputs' ][0]
        print 'uploaded hda!', uploaded_file_data[ 'name' ]
        uploaded_file_id = uploaded_file_data[ '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 )
        uploaded_hda_state = uploaded_hda_details[ 'state' ]

        # here, we'll loop while the uploaded HDA state isn't where we want it
        # NOTE: it may happen that the HDA will error! If that's the case - this will loop
        #   forever. You could press 'ctrl+c' to stop this script - but it's a better
        #   idea to add more code to handle the possibility. We'll be optimistic and
        #   (for simplicity) assume everything will work.
        while uploaded_hda_state != 'ok':
            print '\t uploaded_hda_state:', uploaded_hda_state
            print '\t (waiting 4 seconds...)'
            time.sleep( 4.0 )

            # keep checking to get any new state the HDA might move into
            uploaded_hda_details = hdas_2.get_hda( new_history_id, uploaded_file_id )
            uploaded_hda_state = uploaded_hda_details[ 'state' ]

        # here - we've exited the loop, so the state should be 'ok'
        
    except Exception, exc:
        print 'Error uploading file to history:', str( exc )
        sys.exit( 1 )

    print 'Uploaded:'
    pprint.pprint( uploaded_hda_details, indent=2 )
    print 'State:', uploaded_hda_state
