import requests


def parse_pubinfo(pubmed_id):
    """Download publication information from pubmed."""
    # Fetch json
    r = requests.get('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id={}&retmode=json'.format(pubmed_id))
    pubmed_json = r.json()['result'][str(pubmed_id)]
    # Information of interest for us: author order, title, journal, year, DOI, pages, volume, pubmed_id
    publi_dict = {'pubmed_id': pubmed_id}
    publi_dict['journal'] = pubmed_json['source']
    publi_dict['volume'] = pubmed_json['volume']
    publi_dict['pub_year'] = pubmed_json['sortpubdate'][:4]
    publi_dict['pages'] = pubmed_json['pages']
    # Get doi info
    for x in pubmed_json['articleids']:
        if x['idtype']=='doi':
            publi_dict['doi'] = x['value']
        else:
            continue
    publi_dict['title'] = pubmed_json['title']
    publi_dict['author_order'] = ', '.join([x['name'] for x in pubmed_json['authors']])
    return publi_dict