# -*- coding; utf-8 -*-
from gozerbot.callbacks import callbacks
from gozerbot.plugins import plugins
from gozerbot.plughelp import plughelp
from gozerbot.generic import cchar
from gozerbot.thr import start_new_thread 
import re

plughelp.add('mangle', 'demangles several irssi encoding scripts')

pad = 8
i2b = lambda n: "".join([str((n >> y) & 1) for y in range(pad-1, -1, -1)])
b2i = lambda n: int(n, 2)

re_bin   = re.compile('^([01]{8}( [01]{8})*)( [01]{1,7})*$')
re_morse = re.compile('(^|.*? )([\.\-]+ [\.\- ]+)($| .*)')
morse = {
    'a': '.-',       'b': '-...',     'c': '-.-.',
    'd': '-..',      'e': '.',        'f': '..-.',
    'g': '--.',      'h': '....',     'i': '..',
    'j': '.---',     'k': '-.-',      'l': '.-..',
    'm': '--',       'n': '-.',       'o': '---',
    'p': '.--.',     'q': '--.-',     'r': '.-.',
    's': '...',      't': '-',        'u': '..-',
    'v': '...-',     'w': '.--',      'x': '-..-',
    'y': '-.--',     'z': '--..',     '1': '.----',
    '2': '..---',    '3': '...--',    '4': '....-',
    '5': '.....',    '6': '-....',    '7': '--...',
    '8': '---..',    '9': '----.',    '0': '-----',
    '(': '-.--.',    ')': '-.--.-',   '=': '-...-',
    ':': '---...',   ';': '-.-.-.',   '"': '.-..-.',
    "'": '.----.',   '/': '-..-.',    '@': '.--.-.',
    ',': '--..--',   '.': '.-.-.-',   '\\':'-....-',
    ' ': ' '
}
demorse = dict([(v, k) for k, v in morse.iteritems()])
demorse[''] = ' '

def dispatch(bot, ievent):
    if ievent.txt.startswith(cchar(bot, ievent)):
        if '++' in ievent.txt or '--' in ievent.txt:
            ievent.txt = ievent.txt[1:]
        elif ievent.txt.endswith('?'):
            ievent.txt = ievent.txt[1:]
    if plugins.woulddispatch(bot, ievent):
        start_new_thread(plugins.trydispatch, (bot, ievent))

def handle_privmsg(bot, ievent):
    test_bin   = re_bin.match(ievent.txt)
    test_morse = re_morse.search(ievent.txt)
    if test_bin:
        ievent.txt = ''.join(map(chr, map(b2i, ievent.txt.split(' '))))
        dispatch(bot, ievent)
    elif test_morse:
        ievent.txt = ievent.txt.lower()
        ievent.txt = ''.join(x in demorse and demorse[x] or x for x in ievent.txt.split(' '))
        while '  ' in ievent.txt:
            ievent.txt = ievent.txt.replace('  ', ' ')
        dispatch(bot, ievent)

callbacks.add('PRIVMSG', handle_privmsg)

