# -*- coding: utf-8 -*-

"""
     MoinMoin - macro to embed BibMate publications on a page
"""
import urllib2
from MoinMoin import wikiutil

from MoinMoin import log

logger = log.getLogger(__name__)

BIBMATE_PATH = u'http://bach.ipipan.waw.pl/publications'
 
def macro_BibMate(
        macro, 
        searchBy=('author', 'title', 'key', 'keyword'),
        _trailing_args=[],
        _kwargs=dict(omitYears='false')):
    omitYears = _kwargs['omitYears'].lower()
    
    fmt = macro.formatter
    
    if not omitYears in ['true', 'false']:
        return fmt.rawHTML('<strong>omitYears must have one of two values: "true", "false"</strong>')
    
    query = u'&'.join(
        [u'argument=%s' % urllib2.quote(a.encode('utf-8')) for a in _trailing_args]
        + ['searchBy=%s' % searchBy]
        + ['omitYears=%s' % omitYears]
        )
    path = u'{BIBMATE_PATH}/list/?{QUERY}' \
        .format(
            BIBMATE_PATH=BIBMATE_PATH, 
            QUERY=query)
    uo = None
    try:
        uo = urllib2.urlopen(path)
        html = uo.read()
        return fmt.rawHTML(html).decode('utf-8')
    except:
        logger.exception('Failed to get BibMate data!')
        return fmt.rawHTML('<strong>Failed to fetch publications list!</strong>')
    finally:
        if uo:
            uo.close()

