__module_name__ = "Pygame Documentation Lookup"
__module_version__ = "0.2"
__module_description__ = "References pygame online help"

"""
simple script for use in xchat, use;

/pygame SEARCH
to search for all reference related to SEARCH

/pygame_update
to reload the online documentation
"""



import xchat, urllib, re, sys


Help = {}
Website = 'http://pygame.org/docs/'
Regex = re.compile(r'<a href=(.*)>(.*)</a> - (<b>.*</b>)?(.*)<br>')
Blockwords = 'and', 'or', 'but', 'you', 'if'

def load_help():
    'call to init/reinit the help'
    Help.clear()
    data = urllib.urlopen(Website).readlines()
    helplines = 0
    for line in data:
        line = line.strip()
        if not helplines:
            if line == '<!--FULLINDEX-->': 
                helplines = 1
        else:
            if line == '<!--ENDINDEX-->':
                break
            parse_help_line(line)


def parse_help_line(line):
    match = re.match(Regex, line)
    url, name, isclass, descr = match.groups()
    descr = descr.strip()
    name = name.strip()
    url = Website + url
    if name.startswith('pygame.'):
        name = name[7:]
    fullname = name
    if name.find('.') >= 0:
        name = name.split('.')[-1]
    helpitem = fullname, descr, url
    add_help_item(name, helpitem)
    add_help_item(fullname, helpitem)
    for word in descr.split():
        add_help_item(word, helpitem)


def add_help_item(word, item):
    if Help.has_key(word):
        if not item in Help[word]:
            Help[word].append(item)
    else:
        Help[word] = [item]
    

def find_help(word):
    if word.startswith('pygame.'):
        word = word[7:]
    return Help.get(word)
    


   
    
def pygame_help_lookup(word, word_eol, userdata):
    if len(word) < 2:
        print 'Must provide a term to seach'
        return xchat.EAT_ALL
    if word[1] in Blockwords:
    	print 'Use more specific search word'
	return xchat.EAT_ALL
    xchat.command("me searches pygame docs for '%s'" % (word[1]))
    result = find_help(word[1])
    if not result:
    	xchat.command('say No help found.')
    else:
	for name,descr,url in result:
            xchat.command('say %s - %s'%(name,descr))
            xchat.command('say     %s'%url)
    return xchat.EAT_ALL


def pygame_help_update(word, word_eol, userdata):
    load_help()
    print 'Pygame help reloaded'
    return xchat.EAT_ALL
    
load_help()
xchat.hook_command("pygame", pygame_help_lookup, help="/pygame string_to_lookup") 
xchat.hook_command("pygame_update", pygame_help_update, help="/pygame_update") 
