import json
import requests


def create_remote_version(access_token, version_info, tribe_url):
    """
    Creates a new version for an already existing geneset in Tribe.

    Arguments:
    access_token -- The OAuth token with which the user has access to
    their resources. This is a string of characters.

    version_info -- The dictionary containing the values for the fields
    in the version that is going to be created in Tribe. One of these
    is the resource_uri of the geneset this version will belong to.

    Returns:
    Either -

    a) The newly created version (as a dictionary), or
    b) An empty list, if the request failed.
    """

    headers = {
        'Authorization': 'OAuth ' + access_token,
        'Content-Type': 'application/json'
    }

    payload = json.dumps(version_info)
    versions_url = tribe_url + '/api/v1/version'
    version_response = requests.post(
        versions_url, data=payload, headers=headers
    )

    # If something went wrong and the version was not created
    # (making the response status something other than 201),
    # return the response as is given by Tribe
    if (version_response.status_code != 201):
        return version_response

    try:
        version_response = version_response.json()
        return version_response
    except ValueError:
        return version_response