/****************************************************************************
** ui.h extension file, included from the uic-generated form implementation.
**
** If you wish to add, delete or rename functions or slots use
** Qt Designer which will update this file, preserving your code. Create an
** init() function in place of a constructor, and a destroy() function in
** place of a destructor.
*****************************************************************************/


void DonkeyConfig::init()
{
    binaryButton->setGuiItem(KGuiItem(QString::null, "fileopen"));
    rootButton->setGuiItem(KGuiItem(QString::null, "fileopen"));

    defaultButton->setGuiItem(KGuiItem(i18n("Set as &Default"), "kmldonkey"));
    newButton->setGuiItem(KGuiItem(i18n("New &Core"), "edit_add"));
    deleteButton->setGuiItem(KGuiItem(i18n("D&elete Core"), "editdelete"));

    m_active = 0;
    m_default = 0;
    m_processSignals = true;
}

void DonkeyConfig::configChanged()
{
    emit changed(true);
}

void DonkeyConfig::setDefaultEntry(DonkeyEntry* entry)
{
    if (m_default) m_default->setDefault(false);
    entry->setDefault(true);
    m_default = entry;
    hostList->triggerUpdate(false);
}

void DonkeyConfig::entrySelected(QListBoxItem* item)
{
    if (!m_processSignals) return;
    m_processSignals = false;
    if (item) {
        DonkeyEntry* entry = static_cast<DonkeyEntry*>(item);
        nameEntry->setText(entry->getName());
        addressEntry->setText(entry->getAddress());
        portEntry->setValue(entry->getPort());
        httpPortEntry->setValue(entry->getHTTPPort());
        usernameEntry->setText(entry->getUsername());
        passwordEntry->erase();
        passwordEntry->insert(entry->getPassword());
        hostModeEntry->setCurrentItem(entry->getHostMode());
        hostStack->raiseWidget(entry->getHostMode());
        binaryEntry->setText(entry->getBinary());
        rootEntry->setText(entry->getRoot());
        startupEntry->setCurrentItem(entry->getStartupMode());
        defaultButton->setEnabled(!entry->getDefault());
        deleteButton->setEnabled(true);
        m_active = entry;
        if (!entry->isSelected())
            hostList->setSelected(entry, true);
    } else {
        nameEntry->setText(QString::null);
        addressEntry->setText(QString::null);
        portEntry->setValue(0);
        httpPortEntry->setValue(0);
        usernameEntry->setText(QString::null);
        passwordEntry->erase();
        hostModeEntry->setCurrentItem(0);
        hostStack->raiseWidget(0);
        binaryEntry->setText(QString::null);
        rootEntry->setText(QString::null);
        startupEntry->setCurrentItem(0);
        defaultButton->setEnabled(false);
        deleteButton->setEnabled(false);
        m_active = 0;
    }
    m_processSignals = true;
}

DonkeyEntry* DonkeyConfig::getActiveEntry()
{
    return m_active;
}

void DonkeyConfig::nameChanged(const QString& text)
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setName(text);
    hostList->triggerUpdate(false);
    configChanged();
}

void DonkeyConfig::addressChanged(const QString& text)
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setAddress(text);
    configChanged();
}

void DonkeyConfig::usernameChanged(const QString& text)
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setUsername(text);
    configChanged();
}

void DonkeyConfig::passwordChanged( const QString & )
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setPassword(passwordEntry->password());
    configChanged();
}

void DonkeyConfig::portChanged(int value)
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setPort(value);
    configChanged();
}

void DonkeyConfig::httpPortChanged(int value)
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setHTTPPort(value);
    configChanged();
}

void DonkeyConfig::hostModeChanged(int value)
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setHostMode(value);
    configChanged();
}

void DonkeyConfig::binaryChanged(const QString& value)
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setBinary(value);
    configChanged();
}

void DonkeyConfig::rootChanged(const QString& value)
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setRoot(value);
    configChanged();
}

void DonkeyConfig::startupModeChanged(int value)
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry || !m_processSignals) return;
    entry->setStartupMode(value);
    configChanged();
}

void DonkeyConfig::defaultButtonClicked()
{
    DonkeyEntry* entry = getActiveEntry();
    if (!entry || entry->getDefault()) return;
    setDefaultEntry(entry);
    configChanged();
}

void DonkeyConfig::newButtonClicked()
{
    DonkeyEntry* entry = new DonkeyEntry(hostList, i18n( "New host" ), QString::null,
                                         4001, 4080, QString::null, QString::null);
    if (!m_default) setDefaultEntry(entry);
    hostList->setSelected(entry, true);
    configChanged();
}

void DonkeyConfig::deleteButtonClicked()
{
    DonkeyEntry* entry = getActiveEntry(); if (!entry) return;
    if (m_default == entry) {
	delete entry;
	m_default = 0;
	if (hostList->count())
	    setDefaultEntry(static_cast<DonkeyEntry*>(hostList->firstItem()));
	else
	    m_default = 0;
    } else {
	delete entry;
    }
    configChanged();
}

void DonkeyConfig::rootPathDialog()
{
    KURL dir = KDirSelectDialog::selectDirectory(rootEntry->text(), false, this,
                                                 i18n("Select the MLDonkey Root Folder"));
    if (!dir.isEmpty()) rootEntry->setText(dir.url());
}

void DonkeyConfig::binaryPathDialog()
{
    QString path = KFileDialog::getOpenFileName(binaryEntry->text(), QString::null, this,
                                                i18n("Select the MLDonkey Core"));
    if (!path.isEmpty()) binaryEntry->setText(path);
}

void DonkeyConfig::newMobilePassword()
{
    QCString pw;
    if (KPasswordDialog::getNewPassword(pw, i18n("Enter your new MobileMule password:")) == QDialog::Accepted) {
        KMD5 hash(pw);
        m_mobilePassword = hash.hexDigest();
        mobilePasswordState->setText(i18n("Password is set"));
        configChanged();
    }
}



void DonkeyConfig::save()
{
    KConfig *config = new KConfig("mldonkeyrc", false, false);

    QStringList list = config->groupList();
    QStringList::iterator git;
    for (git = list.begin(); git != list.end(); ++git)
        config->deleteGroup(*git);

    QListBoxItem* it = hostList->firstItem();
    for (; it; it = it->next()) {
        DonkeyEntry* entry = static_cast<DonkeyEntry*>(it);
        config->setGroup(entry->getName());
        config->writeEntry("DonkeyHost", entry->getAddress());
        config->writeEntry("DonkeyGuiPort", entry->getPort());
        config->writeEntry("DonkeyHTTPPort", entry->getHTTPPort());
        config->writeEntry("DonkeyUsername", entry->getUsername());
        config->writeEntry("DonkeyPassword", entry->getPassword());
        config->writeEntry("HostMode", entry->getRealHostMode());
        config->writePathEntry("BinaryPath", entry->getBinary());
        config->writePathEntry("RootPath", entry->getRoot());
        config->writeEntry("StartupMode", entry->getStartupMode());
        config->writeEntry("Default", entry->getDefault());
        if (config->hasKey("LocalHost")) config->deleteEntry("LocalHost");
    }

    config->sync();
    delete config;
    
    config = new KConfig("mobilemulerc", false, false);
    config->setGroup("MobileMule");
    config->writeEntry("Autostart", mobileToggle->isChecked());
    config->writeEntry("Port", mobilePortEntry->value());
    if (!m_mobilePassword.isNull()) {
        if (m_mobilePassword == "blank") {
            if (config->hasKey("Password"))
                config->deleteEntry("Password");
        } else {
            config->writeEntry("Password", m_mobilePassword);
        }
    }
    config->sync();
    delete config;

    startMobileMuleService(mobileToggle->isChecked());

    emit changed(true);
}

void DonkeyConfig::load(bool defaults)
{
    KConfig *config;
    bool foo = false;

    hostList->clear();
    m_default = 0;

    if (!defaults) {
        config = new KConfig("mldonkeyrc", false, false);

        QStringList list = config->groupList();
        QStringList::iterator it;
        for (it = list.begin(); it != list.end(); ++it) {
            bool isDefault;
            config->setGroup(*it);
            int hostMode = config->readNumEntry("HostMode", -1);
            if (hostMode == -1)
                hostMode = config->readBoolEntry("LocalHost", false) ? 1 : 0;
            else if (hostMode == 1)
            	hostMode = 0;
            else if (hostMode == 2)
                hostMode = 1;
            DonkeyEntry* entry = new DonkeyEntry(hostList, *it,
                                                 config->readEntry("DonkeyHost", "localhost"),
                                                 config->readNumEntry("DonkeyGuiPort", 4001),
                                                 config->readNumEntry("DonkeyHTTPPort", 4080),
                                                 config->readEntry("DonkeyUsername", "admin"),
                                                 config->readEntry("DonkeyPassword"),
                                                 hostMode,
                                                 config->readPathEntry("BinaryPath"),
                                                 config->readPathEntry("RootPath"),
                                                 config->readNumEntry("StartupMode", 0),
                                                 isDefault = config->readBoolEntry("Default"));
            if (isDefault) {
                if (m_default)
                    entry->setDefault(false);
                else
                    m_default = entry;
            }
        }
        delete config;
    }

    if (!hostList->count()) {
	m_default = new DonkeyEntry(hostList, "MLDonkey", "localhost", 4001, 4080,
                                    "admin", "", true);
        if (!defaults) {
            foo = true;
            KMessageBox::queuedMessageBox(this, KMessageBox::Information,
                                          i18n("Your KMLDonkey host list was empty, "
                                               "so a default entry has been created "
                                               "for you. "
                                               "Please verify that it contains the "
                                               "correct information."));
        }
    }

    if (!m_default && hostList->count())
	setDefaultEntry(static_cast<DonkeyEntry*>(hostList->firstItem()));

    hostList->sort();

    if (m_default) {
	hostList->setCurrentItem(m_default);
	hostList->centerCurrentItem();
    }

    if (!defaults) {
        config = new KConfig("mobilemulerc", false, false);
        config->setGroup("MobileMule");
        mobileToggle->setChecked(config->readBoolEntry("Autostart", false));
        mobilePortEntry->setValue(config->readNumEntry("Port", 4081));
        if (config->hasKey("Password"))
            mobilePasswordState->setText(i18n("Password is set"));
        else
            mobilePasswordState->setText(i18n("No password set"));
        delete config;
    } else {
        mobileToggle->setChecked(false);
        mobilePortEntry->setValue(4081);
        mobilePasswordState->setText(i18n("No password set"));
        m_mobilePassword = "blank";
    }

    emit changed(foo || defaults);
}

bool DonkeyConfig::startMobileMuleService(bool start)
{
    DCOPClient* client = DCOPClient::mainClient();
    QByteArray data;
    QDataStream arg(data, IO_WriteOnly);
    arg << start;
    return client->send("kded", "mobilemule", "setEnabled(bool)", data);
}


