#!/usr/bin/env python

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

Now with a way to create a history.
"""
import os
import sys
import pprint

import setup
import common

# the REST URL for the user resource
RESOURCE_URL = '/api/histories'

# ----------------------------------------------------------------------------- functions
def get_histories():
    """
    Return a list of dictionaries that describe the current user's histories.
    """
    apikey = setup.get_apikey()
    full_url = setup.get_base_url() + RESOURCE_URL
    return common.get( apikey, full_url )


def get_history( history_id ):
    """
    Return a dictionary that the gives details of a specific current user's history.
    """
    apikey = setup.get_apikey()
    resource_url = setup.get_base_url() + RESOURCE_URL

    full_url = resource_url + '/' + history_id
    return common.get( apikey, full_url )


def create_history( name ):
    """
    Create a history for the current user with the given name.
    :param name: a name for the new history
    """
    # same as get_histories here...
    apikey = setup.get_apikey()
    full_url = setup.get_base_url() + RESOURCE_URL
    # (note: that we don't need an id since we're making a new history
    #           and galaxy will determine its id after creation)

    # ...this time we need to tell the API that we want to create something.
    #   We do this by using the HTTP method 'POST' - in common.py this is done using common.post
    #   Post can take a full dictionary of additional info, but in this case we'll only send the new name
    post_data = { 'name' : name }
    # when creating histories, Galaxy is nice enough to return some data about the new history
    return common.post( apikey, full_url, post_data )


# ----------------------------------------------------------------------------- main
if __name__ == '__main__':
    # again, using an argument - this time, the new history's name
    if len( sys.argv ) <= 1:
        print 'USAGE: histories_3.py <a history name>'
        sys.exit( 1 )

    new_history_name = sys.argv[1]
    # create the history using the function we defined above
    returned = create_history( new_history_name )
    pprint.pprint( returned, indent=2 )
