from typing import OrderedDict


def get_reference(api_output, hashtable):
    """
    Take one result from NKJP api (within <line> tags), extract info
    about autorship and format it for printing

    Args:
        api_output (lxml.etree._Element): one result of NKJP api request,
            i.e. the content within one <line> tag

    Returns:
        str: pretty formated citation. If the source is on the blacklist,
            returns ''
    """
    

    ref = OrderedDict()
    if len(hashtable) == 0:
        ref['authors'] = 'Nazwisko Autora'
    else:
        author_hash = bytes(api_output.find('hash').text, 'utf-8')
        try: ref['authors'] = hashtable[author_hash].decode('utf-8')[4:-5].replace('</au><au>', ', ')
        except KeyError:
            return ''
    
    match = api_output.find('match').text.lower()
    
    excluded_titles = ['Wikipedia:']

    # article title exists for newspaper records
    article_title = api_output.find('title_a')
    if article_title is not None:
        if any(article_title.text.startswith(c) for c in excluded_titles):
            return ''
        elif len(article_title.text) > 0:
            ref['article_title'] = article_title.text



    # this is a book title or a newspaper name
    pub_title = api_output.find('title_mono')
    if pub_title is not None:
        if article_title.text.lower().startswith(match) and 'Wikipedia' in pub_title.text:
            return '' # Wikipedia pages about matched words are probably
            # the best examples
        ref['pub_title'] = pub_title.text.strip()
            
    pub_date = api_output.find('pubDate')
    if pub_date is not None:
        refdate = ''
        if len(pub_date.text) == 8:
            refdate += '{0}/{1}/'.format(pub_date.text[6:], pub_date.text[4:6])
        if len(pub_date.text) in (4, 8):
            refdate += pub_date.text[:4]
        ref['date'] = refdate

    #extras
    for field in ['hash', 'match_start', 'match_end', 'channel', 'domain']:
        ref[field] = api_output.find(field).text

    return ref