# -*- coding: utf-8 -*-
"""
    pyspecific.py
    ~~~~~~~~~~~~~

    Sphinx extension with Python doc-specific markup.

    :copyright: 2008 by Georg Brandl.
    :license: Python license.
"""

ISSUE_URI = 'http://bugs.python.org/issue%s'

from docutils import nodes, utils

def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
    issue = utils.unescape(text)
    text = 'issue ' + issue
    refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
    return [refnode], []

import pickle
seealso_dict = None

def seealsolinks_role(typ, rawtext, text, lineno, inliner, 
                      options={}, content=[]):
    global seealso_dict

    if seealso_dict is None:
        f = open('/tmp/db', 'rb')
	seealso_dict = pickle.load(f)
	f.close()
   
    module_name = utils.unescape(text)

    # Nothing to add
    if module_name not in seealso_dict:
        return [], []

    links = []
    for (url, title, document_url, document_title, 
	 author, excerpt) in seealso_dict[module_name] + seealso_dict['exceptions']:
	page_link = nodes.reference(title, title, refuri=url)
	node = nodes.paragraph()
	node += page_link
	if document_url:
	    msg = ' in '
	    node += nodes.Text(msg, msg)
	    document_link = nodes.reference(document_title,
					    document_title, 
					    refuri=document_url)
	    node += document_link

	if author:
	    msg = ' by ' + author
	    node += nodes.Text(msg, msg)

        node += nodes.Text('.', '.')
	links.append(node)

    return links, []

def setup(app):
    app.add_role('issue', issue_role)
    app.add_role('seealsolinks', seealsolinks_role)
