/***************************************************************************
 *   Copyright (C) 2004-2009 by Thomas Fischer                             *
 *   fischer@unix-ag.uni-kl.de                                             *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_YAZ

#include <qlayout.h>
#include <qtimer.h>
#include <qheader.h>
#include <qlabel.h>
#include <qspinbox.h>
#include <qregexp.h>

#include <klistview.h>
#include <kpushbutton.h>
#include <kiconloader.h>
#include <kdialogbase.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kcombobox.h>
#include <klineedit.h>

#include "settingsz3950.h"

namespace KBibTeX
{

    ServerListViewItem::ServerListViewItem( KListView *list, const QString &_id, Settings::Z3950Server& _server, bool _newItem )
            : KListViewItem( list, _server.name, _server.database ), server( _server ), id( _id ), newItem( _newItem )
    {
        // nothing
    }

    ServerListViewItem::ServerListViewItem( KListViewItem *item, const QString &_id, Settings::Z3950Server& _server, bool _newItem )
            : KListViewItem( item, _server.name, _server.database ), server( _server ), id( _id ), newItem( _newItem )
    {
        // nothing
    }

    void ServerListViewItem::refresh( )
    {
        setText( 0, server.name );
        setText( 1, server.database );
    }

    SettingsZ3950Edit::SettingsZ3950Edit( QString &id, Settings::Z3950Server& _server, QWidget *parent, const char *name )
            : QWidget( parent, name ), m_id( id ), m_server( _server ), m_lineEditId( NULL )
    {
        QGridLayout *layout = new QGridLayout( this, 10, 2 , 0, KDialog::spacingHint() );
        QLabel *label = NULL;

        label = new QLabel( i18n( "Name:" ), this );
        layout->addWidget( label, 1, 0 );
        m_lineEditName = new KLineEdit( m_server.name, this );
        layout->addWidget( m_lineEditName, 1, 1 );
        label->setBuddy( m_lineEditName );

        label = new QLabel( i18n( "Database:" ), this );
        layout->addWidget( label, 2, 0 );
        m_lineEditDatabase = new KLineEdit( m_server.database, this );
        layout->addWidget( m_lineEditDatabase, 2, 1 );
        label->setBuddy( m_lineEditDatabase );

        label = new QLabel( i18n( "Host:" ), this );
        layout->addWidget( label, 3, 0 );
        m_lineEditHost = new KLineEdit( m_server.host, this );
        layout->addWidget( m_lineEditHost, 3, 1 );
        label->setBuddy( m_lineEditHost );

        label = new QLabel( i18n( "Port:" ), this );
        layout->addWidget( label, 4, 0 );
        m_spinBoxPort = new QSpinBox( this );
        m_spinBoxPort->setMinValue( 1 );
        m_spinBoxPort->setMaxValue( 65535 );
        m_spinBoxPort->setValue( m_server.port );
        layout->addWidget( m_spinBoxPort, 4, 1 );
        label->setBuddy( m_spinBoxPort );

        label = new QLabel( i18n( "User:" ), this );
        layout->addWidget( label, 5, 0 );
        m_lineEditUser = new KLineEdit( m_server.user, this );
        layout->addWidget( m_lineEditUser, 5, 1 );
        label->setBuddy( m_lineEditUser );

        label = new QLabel( i18n( "Password:" ), this );
        layout->addWidget( label, 6, 0 );
        m_lineEditPassword = new KLineEdit( m_server.password, this );
        layout->addWidget( m_lineEditPassword, 6, 1 );
        label->setBuddy( m_lineEditPassword );

        label = new QLabel( i18n( "Syntax:" ), this );
        layout->addWidget( label, 7, 0 );
        m_comboBoxSyntax = new KComboBox( true, this );
        layout->addWidget( m_comboBoxSyntax, 7, 1 );
        label->setBuddy( m_comboBoxSyntax );
        m_comboBoxSyntax->insertItem( "grs-1" );
        m_comboBoxSyntax->insertItem( "marc21" );
        m_comboBoxSyntax->insertItem( "mods" );
        m_comboBoxSyntax->insertItem( "unimarc" );
        m_comboBoxSyntax->insertItem( "usmarc" );
        m_comboBoxSyntax->setCurrentText( m_server.syntax );

        label = new QLabel( i18n( "Locale:" ), this );
        layout->addWidget( label, 8, 0 );
        m_comboBoxLocale = new KComboBox( true, this );
        m_comboBoxLocale->setCurrentText( m_server.locale );
        layout->addWidget( m_comboBoxLocale, 8, 1 );
        label->setBuddy( m_comboBoxLocale );

        label = new QLabel( i18n( "Charset:" ), this );
        layout->addWidget( label, 9, 0 );
        m_comboBoxCharset = new KComboBox( true, this );
        layout->addWidget( m_comboBoxCharset, 9, 1 );
        label->setBuddy( m_comboBoxCharset );
        m_comboBoxCharset->insertItem( "iso-5426" );
        m_comboBoxCharset->insertItem( "iso-8859-1" );
        m_comboBoxCharset->insertItem( "marc8" );
        m_comboBoxCharset->insertItem( "marc-8" );
        m_comboBoxCharset->insertItem( "utf-8" );
        m_comboBoxCharset->setCurrentText( m_server.charset );
    }

    SettingsZ3950Edit::~SettingsZ3950Edit()
    {
        // nothing
    }

    int SettingsZ3950Edit::execute( QWidget *parent, QString &id, Settings::Z3950Server &server )
    {
        KDialogBase *dlg = new KDialogBase( parent, "SettingsZ3950Edit", true, i18n( "Edit Z39.50 Server" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, false );
        SettingsZ3950Edit *edit = new SettingsZ3950Edit( id, server, dlg, "SettingsZ3950Edit" );
        dlg->setMainWidget( edit );
        connect( dlg, SIGNAL( apply() ), edit, SLOT( slotApply() ) );
        connect( dlg, SIGNAL( okClicked() ), edit, SLOT( slotApply() ) );

        return dlg->exec();
    }

    void SettingsZ3950Edit::slotApply()
    {
        m_server.charset = m_comboBoxCharset->currentText();
        m_server.database = m_lineEditDatabase->text();
        m_server.host = m_lineEditHost->text();
        m_server.locale = m_comboBoxLocale->currentText();
        m_server.name = m_lineEditName->text();
        m_server.syntax = m_comboBoxSyntax->currentText();
        m_server.user = m_lineEditUser->text();
        m_server.password = m_lineEditPassword->text();
        m_server.port = m_spinBoxPort->value();

        if ( m_id.isEmpty() )
        {
            m_id = QString( m_server.name ).lower().replace( QRegExp( "[^a-z0-9]" ), "" );
            qDebug( "Setting id to %s", m_id.latin1() );
        }
    }

    SettingsZ3950::SettingsZ3950( QWidget *parent, const char *name )
            : QWidget( parent, name )
    {
        setupGUI();
    }

    SettingsZ3950::~SettingsZ3950()
    {
        // nothing
    }

    void SettingsZ3950::applyData()
    {
        Settings *settings = Settings::self();
        settings->z3950_ServerList.clear();

        for ( QListViewItemIterator it( m_listServers ); it.current(); ++it )
        {
            ServerListViewItem *item = dynamic_cast<ServerListViewItem*>( *it );
            settings->z3950_ServerList[item->id] = item->server;
        }
    }

    void SettingsZ3950::readData()
    {
        Settings *settings = Settings::self();
        m_listServers->clear();

        for ( QMap<QString, Settings::Z3950Server>::Iterator it = settings->z3950_ServerList.begin(); it != settings-> z3950_ServerList.end(); ++it )
        {
            ServerListViewItem *item = new ServerListViewItem( m_listServers, it.key(), it.data(), false );
            item->setPixmap( 0, SmallIcon( "server" ) );
        }

        updateGUI();
    }

    void SettingsZ3950::slotNewServer()
    {
        Settings::Z3950Server server;
        server.port = 2100;
        ServerListViewItem * item = new ServerListViewItem( m_listServers, "", server, true );
        item->setPixmap( 0, SmallIcon( "server" ) );
        m_listServers->setSelected( item, TRUE );
        QTimer::singleShot( 100, this, SLOT( slotEditServer() ) );
    }

    void SettingsZ3950::slotEditServer()
    {
        ServerListViewItem * item = static_cast<ServerListViewItem*>( m_listServers->selectedItem() );
        if ( item != NULL )
        {
            if ( SettingsZ3950Edit::execute( this, item->id, item->server ) == QDialog::Accepted )
            {
                item->refresh();
                emit configChanged();
            }
            else if ( item->newItem )
            {
                delete item;
                updateGUI();
            }
        }
    }

    void SettingsZ3950::slotDeleteServer()
    {
        delete m_listServers->selectedItem();
        emit configChanged();
        updateGUI();
    }

    void SettingsZ3950::slotMoveUpServer()
    {
        ServerListViewItem * item = dynamic_cast<ServerListViewItem*>( m_listServers->selectedItem() );
        ServerListViewItem *itemAbove = NULL;
        if ( item != NULL && ( itemAbove = dynamic_cast<ServerListViewItem*>( item->itemAbove() ) ) != NULL )
        {
            Settings::Z3950Server server = item->server;
            item->server = itemAbove->server;
            itemAbove->server = server;
            QString id = item->id;
            item->id = itemAbove->id;
            itemAbove->id = id;
            for ( int i = 0; i < 2; ++i )
            {
                QString swap = item->text( i );
                item->setText( i, itemAbove->text( i ) );
                itemAbove->setText( i, swap );
            }
            m_listServers->setCurrentItem( itemAbove );
            m_listServers->ensureItemVisible( itemAbove );
        }
    }

    void SettingsZ3950::slotMoveDownServer()
    {
        ServerListViewItem * item = dynamic_cast<ServerListViewItem*>( m_listServers->selectedItem() );
        ServerListViewItem *itemBelow = NULL;
        if ( item != NULL && ( itemBelow = dynamic_cast<ServerListViewItem*>( item->itemBelow() ) ) != NULL )
        {
            Settings::Z3950Server server = item->server;
            item->server = itemBelow->server;
            itemBelow->server = server;
            QString id = item->id;
            item->id = itemBelow->id;
            itemBelow->id = id;
            for ( int i = 0; i < 2; ++i )
            {
                QString swap = item->text( i );
                item->setText( i, itemBelow->text( i ) );
                itemBelow->setText( i, swap );
            }
            m_listServers->setCurrentItem( itemBelow );
            m_listServers->ensureItemVisible( itemBelow );
        }
    }

    void SettingsZ3950::slotResetToDefault()
    {
        if ( KMessageBox::warningContinueCancel( this, i18n( "All Z39.50 server configurations will be reset to defaults." ), i18n( "Reset to Default" ), KGuiItem( i18n( "Reset" ), "reload" ) ) == KMessageBox::Continue )
        {
            Settings *settings = Settings::self();
            settings->z3950clearAll();
            settings->z3950loadDefault();
            readData();
        }
    }

    void SettingsZ3950::updateGUI()
    {
        QListViewItem *item = m_listServers->selectedItem();
        bool selected = item != NULL;
        m_buttonEditServer->setEnabled( selected );
        m_buttonDeleteServer->setEnabled( selected );
        m_buttonMoveDownServer->setEnabled( selected && item->itemBelow() != NULL );
        m_buttonMoveUpServer->setEnabled( selected && item->itemAbove() != NULL );
    }

    void SettingsZ3950::setupGUI()
    {
        QGridLayout * gridLayout = new QGridLayout( this, 7, 2, 0, KDialog::spacingHint(), "gridLayout" );
        gridLayout->setRowStretch( 5, 1 );
        gridLayout->setColStretch( 0, 1 );

        m_listServers = new KListView( this );
        m_listServers->setSorting( -1, FALSE );
        m_listServers->addColumn( i18n( "z3950 server", "Name" ) );
        m_listServers->addColumn( i18n( "z3950 server", "Database" ) );
        m_listServers->header()->setClickEnabled( FALSE );
        m_listServers->setFullWidth( true );
        m_listServers->setAllColumnsShowFocus( true );
        gridLayout->addMultiCellWidget( m_listServers, 0, 7, 0, 0 );
        connect( m_listServers, SIGNAL( selectionChanged() ), this, SLOT( updateGUI() ) );
        connect( m_listServers, SIGNAL( currentChanged( QListViewItem * ) ), this, SLOT( updateGUI() ) );
        connect( m_listServers, SIGNAL( doubleClicked( QListViewItem*, const QPoint &, int ) ), this, SLOT( slotEditServer() ) );

        m_buttonNewServer = new KPushButton( i18n( "z3950 server",  "New" ), this );
        m_buttonNewServer->setIconSet( QIconSet( SmallIcon( "add" ) ) );
        gridLayout->addWidget( m_buttonNewServer, 0, 1 );
        connect( m_buttonNewServer, SIGNAL( clicked() ), this, SLOT( slotNewServer() ) );
        m_buttonEditServer = new KPushButton( i18n( "z3950 server", "Edit" ), this );
        m_buttonEditServer->setIconSet( QIconSet( SmallIcon( "edit" ) ) );
        gridLayout->addWidget( m_buttonEditServer, 1, 1 );
        connect( m_buttonEditServer, SIGNAL( clicked() ), this, SLOT( slotEditServer() ) );
        m_buttonDeleteServer = new KPushButton( i18n( "z3950 server", "Delete" ), this );
        m_buttonDeleteServer->setIconSet( QIconSet( SmallIcon( "editdelete" ) ) );
        gridLayout->addWidget( m_buttonDeleteServer, 2, 1 );
        connect( m_buttonDeleteServer, SIGNAL( clicked() ), this, SLOT( slotDeleteServer() ) );
        m_buttonMoveUpServer = new KPushButton( i18n( "z3950 server", "Up" ), this );
        m_buttonMoveUpServer->setIconSet( QIconSet( SmallIcon( "up" ) ) );
        gridLayout->addWidget( m_buttonMoveUpServer, 3, 1 );
        connect( m_buttonMoveUpServer, SIGNAL( clicked() ), this, SLOT( slotMoveUpServer() ) );
        m_buttonMoveDownServer = new KPushButton( i18n( "z3950 server", "Down" ), this );
        m_buttonMoveDownServer->setIconSet( QIconSet( SmallIcon( "down" ) ) );
        gridLayout->addWidget( m_buttonMoveDownServer, 4, 1 );
        connect( m_buttonMoveDownServer, SIGNAL( clicked() ), this, SLOT( slotMoveDownServer() ) );

        m_buttonResetToDefault = new KPushButton( i18n( "z3950 server", "Reset" ), this );
        m_buttonResetToDefault->setIconSet( QIconSet( SmallIcon( "reload" ) ) );
        gridLayout->addWidget( m_buttonResetToDefault, 6, 1 );
        connect( m_buttonResetToDefault, SIGNAL( clicked() ), this, SLOT( slotResetToDefault() ) );
    }

}
#include "settingsz3950.moc"

#endif // HAVE_YAZ
