# aspell wrapper, checks spelling
# Wijnand 'tehmaze' Modderman - http://tehmaze.com
# BSD License

from gozerbot.commands import cmnds
from gozerbot.generic import gozerpopen
import tempfile
import os

def handle_spell(bot, ievent):
    usage = '<-[lang]> <word or sentence>, where [lang] is a country code, like "en" for English, "de" for German, etc.'
    if not ievent.args:
        return ievent.missing(usage)
    args = ievent.args
    lang = 'en'
    if args[0].startswith('-'):
        if len(args[0]) != 3:
            return ievent.missing(usage)
        lang = args[0][1:]
        args = args[1:]
    if not args:
        return ievent.reply(usage)
    cmnd = ['aspell', '-a', '-l', lang]
    proces = gozerpopen(cmnd, [])
    proces.tochild.write(' '.join(args))
    proces.tochild.close()
    data = proces.fromchild.readlines()
    returncode = proces.close()
    if returncode > 0:
        return ievent.reply('error running aspell, the language of your choice might not be available')
    reply = []
    for line in data:
        line = line.strip()
        if line.startswith('&'):
            word, suggest = line[1:].split(': ', 1)
            word = word.split()[0].strip()
            reply.append('%s misspelled, suggestions: %s' % (word, suggest))
        elif line.startswith('#'):
            word = line[2:].split()[0]
            reply.append('%s misspelled, no suggestions' % word)
    if not reply:
        ievent.reply('spelling ok')
    else:
        ievent.reply(', '.join(reply))

cmnds.add('spell', handle_spell, 'USER')

def handle_spelllist(bot, ievent):
    cmnd = ['aspell', 'dump', 'dicts']
    proces = gozerpopen(cmnd, [])
    data = proces.fromchild.readlines()
    returncode = proces.close()
    if returncode > 0:
        return ievent.reply('error running aspell, it might not be available')
    langs = [x.strip() for x in data]
    ievent.reply('available languages: %s' % ', '.join(langs))

cmnds.add('spell-list', handle_spelllist, 'USER')

