import requests


def zenodo_file_download_helper(auth_parameter, is_record, project_name, metadata_helper, files):
    """
    Downloads a single file from Zenodo and returns the expected dictionary.

    Parameters
    ----------
    auth_parameter : dict
        The Authentication parameter expected by Zenodo.
    is_record : bool
        Flag for if the resource is a published record
    project_name : str
        The name of the project.
    metadata_helper : dict
        JSON payload from Zenodo API
    files: list
        The list to append the file to.

    Returns
    -------
        The list of files.
    """
    if is_record is True:
        file_contents = requests.get(
            metadata_helper['contents'][0]['links']['self'], params=auth_parameter).content
        hashes = {'md5': metadata_helper['contents'][0]['checksum'].partition(':')[2]}
        title = metadata_helper['contents'][0]['key']
        path = '/{}'.format(title)
        # No way of getting project title if passed a file id.
        source_path = '/{}'.format(title)
    else:
        file_contents = requests.get(
            metadata_helper['links']['download'], params=auth_parameter).content
        hashes = {'md5': metadata_helper['checksum']}
        title = metadata_helper['filename']
        path = '/{}'.format(metadata_helper['filename'])
        source_path = "/{}/{}".format(project_name, metadata_helper['filename'])

    files.append({
        'file': file_contents,
        'hashes': hashes,
        'title': title,
        # If the file is the only resource we are downloading then we don't need it's full path.
        'path': path,
        'source_path': source_path,
        'extra_metadata': {}})

    return files