/* -*- c++ -*-
 *
 * shareddirs.cpp
 *
 * Copyright (C) 2003 Sebastian Sauer <mail@dipe.org>
 *                    Petter Stokke <ummo@hellokitty.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 2
 * of the License, or (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, write to the Free Software
 * Foundation, Inc., 51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <qlayout.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <qhgroupbox.h>

#include <kglobal.h>
#include <kconfig.h>
#include <klocale.h>
#include <kdebug.h>
#include <kpushbutton.h>
#include <klistview.h>
#include <klineedit.h>
#include <knuminput.h>
#include <kmessagebox.h>
#include <kdirselectdialog.h>

#include "infolist.h"
#include "prefs.h"
#include "kmldonkey.h"

#include "hostmanager.h"

#include "shareddirs.h"
#include "shareddirs.moc"

void applySharesConsoleCallback::callback(const QString& cmd, const QString& res)
{
    count--;
    list << i18n("%1: %2").arg(cmd).arg(res);
    if (count == 0)
        KMessageBox::informationList(KMLDonkey::App, i18n("Messages from core about applied changes."), list, i18n("Shared Folders"));
}


void sharesConsoleCallback::callback(const QString& /*cmd*/, const QString& res)
{
    QStringList list = QStringList::split("\n", res);
    for (QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
        QString s = (*it).stripWhiteSpace();
        int pos = s.find(" ");
        if (pos < 0) continue;

        bool ok;
        int prio = s.left(pos).toInt(&ok);
        if (! ok) continue;
        QString dir = s.right(s.length() - pos - 1).stripWhiteSpace();
        if(dlg->shareddirs.contains(dir)) continue;

        if (dlg->addItem(dir, prio))
            dlg->shareddirs.replace(dir, prio);
    }
    dlg->setEnabled();
}

SharedDirsDialog::SharedDirsDialog(QWidget* parent, const char* name)
    : KDialogBase(Plain, i18n("Shared Folders"), Ok | Cancel, Cancel, parent, name)
{
    applyCallback = 0;

    QHBoxLayout* layout = new QHBoxLayout(plainPage());
    QHGroupBox *grpBox = new QHGroupBox(i18n("Shared Folders"), plainPage());
    layout->addWidget(grpBox);

    QVBox *vbox = new QVBox(grpBox);
    vbox->setSpacing(6);

    // Listview
    view = new KListView(vbox);
    view->setAllColumnsShowFocus(true);
    view->addColumn(i18n("Folder"));
    view->addColumn(i18n("Priority"));
    connect(view, SIGNAL( selectionChanged() ), this, SLOT( slotSelectionChanged() ));

    // Buttons
    QHBox *btnBox = new QHBox(vbox);
    btnBox->setSpacing(6);

    btnAdd = new KPushButton(i18n("&Add"), btnBox);
    QToolTip::add(btnAdd, i18n("Add shared folder"));
    btnAdd->setEnabled(false);
    connect(btnAdd, SIGNAL( clicked() ), this, SLOT( slotAdd() ));

    btnRemove = new KPushButton(i18n("&Remove"), btnBox);
    QToolTip::add(btnRemove, i18n("Remove shared folder"));
    btnRemove->setEnabled(false);
    connect(btnRemove, SIGNAL( clicked() ), this, SLOT( slotRemove() ));

    // Edit
    editBox = new QVBox(grpBox);
    editBox->setSpacing(6);
    editBox->setEnabled(false);

    QHBox *hb1 = new QHBox(editBox);
    hb1->setSpacing(2);
    new QLabel(i18n("Folder:"), hb1);
    editDir = new KLineEdit(hb1);
    connect(editDir, SIGNAL( textChanged(const QString &) ), this, SLOT( slotEditChanged() ));
    if (KMLDonkey::App->hostManager->hostType(KMLDonkey::App->lastHost) != HostInterface::External) {
        KPushButton *editBtn = new KPushButton(KGuiItem(QString::null, "fileopen"), hb1);
        QToolTip::add(editBtn, i18n("Browse folders"));
        connect(editBtn, SIGNAL( clicked() ), this, SLOT( slotDirPath() ));
    }

    QHBox *hb2 = new QHBox(editBox);
    hb2->setSpacing(2);
    new QLabel(i18n("Priority:"), hb2);
    editPrio = new KIntNumInput(hb2);
    connect(editPrio, SIGNAL( valueChanged(int) ), this, SLOT( slotPrioChanged() ));

    editBox->setStretchFactor(new QWidget(editBox), 1);

    enableButton(Ok, false);
    connect(this, SIGNAL( okClicked() ), this, SLOT( applyChanges() ));
    connect(this, SIGNAL( finished() ), this, SLOT( closeDialog() ));

    enabled = false;
    if (KMLDonkey::App->donkey->isConnected()) {
        sharesConsoleCallback *sharesCallback = new sharesConsoleCallback;
        sharesCallback->dlg = this;
        KMLDonkey::App->donkey->sendConsoleMessage("shares", sharesCallback);
    }
}

SharedDirsDialog::~SharedDirsDialog()
{
    // FIXME: We can't delete applyCallback here cause
    // it's callback-function will be called later, but
    // we need to free it at some point.
    //delete applyCallback; applyCallback = 0;
}

void SharedDirsDialog::setEnabled()
{
    if (! enabled) {
        enabled = true;
        btnAdd->setEnabled(true);
        enableButton(Ok, true);
    }
}

KListViewItem* SharedDirsDialog::addItem(QString dir, int prio)
{
    KListViewItem *item = new KListViewItem(view);
    item->setText(0, dir);
    item->setText(1, QString::number(prio));
    return item;
}

void SharedDirsDialog::slotSelectionChanged()
{
    bool b = enabled && view->selectedItem();
    btnRemove->setEnabled(b);
    editBox->setEnabled(b);
    editDir->setText( b ? view->selectedItem()->text(0) : QString("") );
    editPrio->setValue( b ? view->selectedItem()->text(1).toInt() : 0 );
}

void SharedDirsDialog::slotAdd()
{
    view->setCurrentItem( addItem("", 0) );
    editDir->setFocus();
}

void SharedDirsDialog::slotRemove()
{
    QListViewItem *item = view->selectedItem();
    if (item) view->takeItem(item);
}

void SharedDirsDialog::slotEditChanged()
{
    QListViewItem *item = view->selectedItem();
    if (item) item->setText(0, editDir->text());
}

void SharedDirsDialog::slotPrioChanged()
{
    QListViewItem *item = view->selectedItem();
    if (item) item->setText(1, QString::number(editPrio->value()));
}

void SharedDirsDialog::slotDirPath()
{
    KURL dir = KDirSelectDialog::selectDirectory(editDir->text(), false, this, i18n("Select Folder"));
    if (! dir.isEmpty()) editDir->setText( dir.path() );
}

void SharedDirsDialog::applyChanges()
{
    if (! applyCallback)
        applyCallback = new applySharesConsoleCallback();

    applyCallback->count = 0;
    applyCallback->list.clear();

    QString s;
    bool b;
    QListViewItemIterator vit( view );
    for ( ; vit.current(); ++vit) {
        QString s = vit.current()->text(0);
        int i = vit.current()->text(1).toInt(&b);
        if ( (! shareddirs.contains(s) || shareddirs[s] != i) && ! s.isEmpty() && b) {
            applyCallback->count++;
            KMLDonkey::App->donkey->sendConsoleMessage("share " + QString::number(i) + " \"" + s + "\"", applyCallback);
        }
        if (shareddirs.contains(s))
            shareddirs.remove(s);
    }

    for (QMap<QString,int>::iterator sit = shareddirs.begin(); sit != shareddirs.end(); ++sit) {
        applyCallback->count++;
        KMLDonkey::App->donkey->sendConsoleMessage("unshare \"" + sit.key() + "\"", applyCallback);
    }
}

void SharedDirsDialog::closeDialog()
{
    delayedDestruct();
}

