import requests


def goa_file(user_request, filedir='./', tarfile='', option='file', cookie='', verbose=False):
    """
    Query the GOA to download a FITS file, TAR files, or preview PNG.

    Parameters
        user_request:   Search request URL string, it should not contain 'file', 'preview', or 'download'
        filedir:        Directory for the resulting file
        tarfile:        Name of the tar file if the option is 'download'
        option:         Valid options are file, preview, and download
        cookie:         Unique browser cookie for authentication, only needed to download proprietary data

    Return
        filename:       The name of the file that was written
    """

    options = ['file', 'preview', 'download']
    if option not in options:
        print('goa:file: option must be one of {}'.format(options))
        raise ValueError('Option must be one of {}'.format(options))

    l_user_request = user_request

    if option == 'download':
        if tarfile.strip() != '':
            filename = tarfile
        else:
            filename = 'gemini_data.tar'
    else:
        l_user_request = l_user_request.strip('.bz2')
        filename = l_user_request

    if option == 'preview':
        filename = filename + '.jpeg'

    response = requests.get(
        'https://archive.gemini.edu/' + option + '/' + l_user_request,
        headers={'Cookie': 'gemini_archive_session={}'.format(cookie)},
        stream=True
    )
    try:
        response.raise_for_status()
    except requests.exceptions.HTTPError as exc:
        print('goa_file: request failed: {}'.format(response.text))
        raise exc
    else:
        with open(filedir + filename, 'wb') as fd:
            for chunk in response.iter_content(chunk_size=128):
                fd.write(chunk)

    if verbose:
        print(response.url)

    return filename