# mootools stuffs

from gozerbot.callbacks import callbacks
from gozerbot.commands import cmnds
from gozerbot.generic import cchar, geturl2
from gozerbot.persistconfig import PersistConfig
from gozerbot.users import users
import re

cfg = PersistConfig()
cfg.define('docs', 'http://docs.mootools.net')
cfg.define('kick-reason', 'Ask you mom if you can take accordion playing lessons, ta')

class Mootools:
    docurls = [
        'http://docs.mootools.net/index/General',
        'http://docs.mootools.net/index/General2',
        'http://docs.mootools.net/index/General3',
        'http://docs.mootools.net/index/General4',
        ]
    re_link = re.compile('<a href="([^"]+)"[^>]+>', re.S)

    def __init__(self):
        self.docs = {}
        self.get_docs()

    def add_doc(self, base, link):
        base = base.lower()
        base = base.replace(' ', '')
        if not self.docs.has_key(base):
            self.docs[base] = []
        if not link.startswith('http://'):
            if link.startswith('../'):
                link = link.replace('../', '/')
            self.docs[base].append(cfg.get('docs') + link)
        else:
            self.docs[base].append(link)

    def get_docs(self):
        for url in self.docurls:
            try:
                html = geturl2(url)
            except:
                continue
            stat = 'one'
            base = ''
            for line in html.splitlines():
                line = line.strip()
                if line.startswith('<a href="'):
                    links = []
                    if stat == 'one':
                        links = self.re_link.findall(line)
                        base = line.split('>')[1].split('<')[0].lower()
                    elif stat == 'sub':
                        links = self.re_link.findall(line)
                    if links:
                        for link in links:
                            self.add_doc(base, link)
                elif line.startswith('<td class="IEntry">'):
                    stat = 'one'
                    base = ''
                elif line.startswith('<div class="ISubIndex">'):
                    stat = 'sub'
                elif line.startswith('<span class="ISymbol">'):
                    base = line.split('>')[1].split('<')[0].lower()

mootools = Mootools()

def handle_moodoc(bot, ievent):
    if not ievent.args:
        ievent.missing('<class|event|file|function|property>')
        return
    if not mootools.docs.has_key(ievent.args[0].lower()):
        ievent.reply('not found')
    else:
        ievent.reply(mootools.docs[ievent.args[0].lower()], dot=True)

cmnds.add('moodoc', handle_moodoc, 'USER')

def handle_moodoclist(bot, ievent):
    docs = list(mootools.docs.keys())
    docs.sort()
    ievent.reply('docs items:', result=docs, nritems=True)

cmnds.add('moodoc-list', handle_moodoclist, 'USER')

def joincb(bot, ievent):
    if ievent.channel.lower() == '#mootools' and ievent.nick.lower() == bot.nick.lower():
        bot.sendraw('PRIVMSG ChanServ :op %s' % ievent.channel)

callbacks.add('JOIN', joincb)

def privmsgcb(bot, ievent):
    if not hasattr(ievent, 'channel') or ievent.channel.lower() != '#mootools':
        return
    if 'accordion' in ievent.txt.lower():
        perms = users.getperms(ievent.userhost)
        if 'MOOOPER' in perms or 'OPER' in perms:
            return 
        bot.sendraw('KICK %s %s :%s' % (ievent.channel, ievent.nick, cfg.get('kick-reason')))
        bot.sendraw('INVITE %s %s' % (ievent.nick, ievent.channel))
        return
    if ievent.txt[0] == cchar(bot, ievent) and ievent.txt.split()[0][1:].lower() in ['doc', 'docs']:
        ievent.args = ievent.txt.split()[1:]
        handle_moodoc(bot, ievent)
    
callbacks.add('PRIVMSG', privmsgcb)

