/*
   This file is part of MDic Dictionary

   Copyright (C) 2007-2010 Mehrdad Momeny <mehrdad.momeny@gmail.com
   Copyright (C) 2007-2010 Majid Ramezanpour <majid.ramezanpour@gmail.com>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License,
   (at your option) any later version

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details

   You should have received a copy of the GNU General Public License
   along with this program; if not, see http://www.gnu.org/licenses/
*/

#include "mdicaspell.h"
#include <QString>
#include <QStringList>
#include <settings.h>


QPointer<MDicAspell> MDicAspell::m_self = 0L;

MDicAspell* MDicAspell::self()
{
    if (!m_self)
        m_self = new MDicAspell();
    return m_self;
}

MDicAspell::MDicAspell()
{
    config = Settings::self();

    spell_config = new_aspell_config();
    aspell_config_replace(spell_config, "lang", config->spellingLang.toLatin1().data());
    possible_err = new_aspell_speller(spell_config);

    spell_checker = 0;

    if (aspell_error_number(possible_err) != 0)
        puts(aspell_error_message(possible_err));
    else
        spell_checker = to_aspell_speller(possible_err);
}


QStringList MDicAspell::spell(const QString& phrase)
{
    wordsList.clear();
    int correct = aspell_speller_check(spell_checker, phrase.toUtf8().data(), phrase.toUtf8().size());

    if (!correct) {
        const AspellWordList * suggestions = aspell_speller_suggest(spell_checker,
                                             phrase.toUtf8().data(), phrase.toUtf8().size());
        AspellStringEnumeration * elements = aspell_word_list_elements(suggestions);

        const char * word;
        while ((word = aspell_string_enumeration_next(elements)) != NULL) {
            wordsList.append(QString::fromUtf8(word));
        }
        delete_aspell_string_enumeration(elements);
    }

    return wordsList;
}



MDicAspell::~MDicAspell()
{
    delete_aspell_speller(spell_checker);

}



#include "mdicaspell.moc"
