/***************************************************************************
 *   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 <tqlayout.h>
#include <tqtimer.h>
#include <tqheader.h>
#include <tqlabel.h>
#include <tqspinbox.h>
#include <tqregexp.h>

#include <tdelistview.h>
#include <kpushbutton.h>
#include <kiconloader.h>
#include <kdialogbase.h>
#include <tdemessagebox.h>
#include <tdelocale.h>
#include <kcombobox.h>
#include <klineedit.h>

#include "settingsz3950.h"

namespace KBibTeX
{

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

    ServerListViewItem::ServerListViewItem( TDEListViewItem *item, const TQString &_id, Settings::Z3950Server& _server, bool _newItem )
            : TDEListViewItem( 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( TQString &id, Settings::Z3950Server& _server, TQWidget *parent, const char *name )
            : TQWidget( parent, name ), m_id( id ), m_server( _server ), m_lineEditId( NULL )
    {
        TQGridLayout *layout = new TQGridLayout( this, 10, 2 , 0, KDialog::spacingHint() );
        TQLabel *label = NULL;

        label = new TQLabel( 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 TQLabel( 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 TQLabel( 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 TQLabel( i18n( "Port:" ), this );
        layout->addWidget( label, 4, 0 );
        m_spinBoxPort = new TQSpinBox( 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 TQLabel( 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 TQLabel( 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 TQLabel( 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 TQLabel( 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 TQLabel( 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( TQWidget *parent, TQString &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, TQ_SIGNAL( apply() ), edit, TQ_SLOT( slotApply() ) );
        connect( dlg, TQ_SIGNAL( okClicked() ), edit, TQ_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 = TQString( m_server.name ).lower().replace( TQRegExp( "[^a-z0-9]" ), "" );
            tqDebug( "Setting id to %s", m_id.latin1() );
        }
    }

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

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

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

        for ( TQListViewItemIterator 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 ( TQMap<TQString, 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 );
        TQTimer::singleShot( 100, this, TQ_SLOT( slotEditServer() ) );
    }

    void SettingsZ3950::slotEditServer()
    {
        ServerListViewItem * item = static_cast<ServerListViewItem*>( m_listServers->selectedItem() );
        if ( item != NULL )
        {
            if ( SettingsZ3950Edit::execute( this, item->id, item->server ) == TQDialog::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;
            TQString id = item->id;
            item->id = itemAbove->id;
            itemAbove->id = id;
            for ( int i = 0; i < 2; ++i )
            {
                TQString 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;
            TQString id = item->id;
            item->id = itemBelow->id;
            itemBelow->id = id;
            for ( int i = 0; i < 2; ++i )
            {
                TQString 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()
    {
        TQListViewItem *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()
    {
        TQGridLayout * gridLayout = new TQGridLayout( this, 7, 2, 0, KDialog::spacingHint(), "gridLayout" );
        gridLayout->setRowStretch( 5, 1 );
        gridLayout->setColStretch( 0, 1 );

        m_listServers = new TDEListView( 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, TQ_SIGNAL( selectionChanged() ), this, TQ_SLOT( updateGUI() ) );
        connect( m_listServers, TQ_SIGNAL( currentChanged( TQListViewItem * ) ), this, TQ_SLOT( updateGUI() ) );
        connect( m_listServers, TQ_SIGNAL( doubleClicked( TQListViewItem*, const TQPoint &, int ) ), this, TQ_SLOT( slotEditServer() ) );

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

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

}
#include "settingsz3950.moc"

#endif // HAVE_YAZ
