/* ============================================================
 *
 * This file is a part of kipi-plugins project
 * http://www.kipi-plugins.org
 *
 * Date        : 2003-02-17
 * Description : a kipi plugin to slide images.
 *
 * Copyright (C) 2006-2007 by Valerio Fuoglio <valerio dot fuoglio at gmail dot com>
 * Copyright (C) 2003-2005 by Renchi Raju <renchi@pooh.tam.uiuc.edu>
 *
 * 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, 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.
 *
 * ============================================================ */

// TQt includes.

#include <tqbuttongroup.h>
#include <tqcheckbox.h>
#include <tqcombobox.h>
#include <tqlabel.h>
#include <tqradiobutton.h>
#include <tqspinbox.h>
#include <tqlayout.h>
#include <tqmap.h>
#include <tqframe.h>
#include <tqpushbutton.h>
#include <tqtabwidget.h>
#include <tqcolor.h>
#include <tqnamespace.h>
#include <tqlistbox.h>
#include <tqfileinfo.h>

// Kde includes.

#include <tdelocale.h>
#include <tdeconfig.h>
#include <tdemessagebox.h>
#include <tdeapplication.h>
#include <tdeaboutdata.h>
#include <khelpmenu.h>
#include <kiconloader.h>
#include <tdepopupmenu.h>
#include <tdestandarddirs.h>
#include <tdefontdialog.h>
#include <kcolorbutton.h>
#include <tdeio/previewjob.h>
#include <kurl.h>

// libkipi includes

#include <libkipi/interface.h>
#include <libkipi/imagedialog.h>

// Local includes.

#include "kpaboutdata.h"
#include "pluginsversion.h"
#include "listimageitems.h"
#include "slideshow.h"
#include "slideshowgl.h"
#include "slideshowkb.h"
#include "slideshowconfig.h"
#include "slideshowconfig.moc"

namespace KIPISlideShowPlugin
{

SlideShowConfig::SlideShowConfig(bool allowSelectedOnly, KIPI::Interface * interface, 
                                 TQWidget *parent, const char* name, bool ImagesHasComments,
                                 KURL::List *urlList)
               : SlideShowConfigBase(parent, name) 
{
    // About data and help button.

    KIPIPlugins::KPAboutData * about = new KIPIPlugins::KPAboutData(I18N_NOOP("Slide Show"),
                                        0,
                                        TDEAboutData::License_GPL,
                                        I18N_NOOP("A Kipi plugin for image slideshow"),
                                        "(c) 2003-2004, Renchi Raju\n(c) 2007, Valerio Fuoglio");

    about->addAuthor("Renchi Raju", I18N_NOOP("Author"),
                     "renchi@pooh.tam.uiuc.edu");
    about->addAuthor("Valerio Fuoglio", I18N_NOOP("Author and maintainer"),
                     "valerio.fuoglio@gmail.com");

    KHelpMenu* helpMenu = new KHelpMenu(this, about, false);
    helpMenu->menu()->removeItemAt(0);
    helpMenu->menu()->insertItem(i18n("Plugin Handbook"), this, TQ_SLOT(slotHelp()), 0, -1, 0);
    m_helpButton->setPopup( helpMenu->menu() );

    // Switch to selected files only (it depends on allowSelectedOnly)

    m_selectedFilesButton->setEnabled( allowSelectedOnly );

    m_delayMsMaxValue = 100000;
    m_delayMsMinValue = 100;
    m_delayMsLineStep = 10;
    
    m_delaySpinBox->setMinValue(m_delayMsMinValue);
    m_delaySpinBox->setMaxValue(m_delayMsMaxValue);
    m_delaySpinBox->setLineStep(m_delayMsLineStep); 
    
    m_interface = interface;
    
    // Signal to Slot connections

    connect(m_openglCheckBox, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotOpenGLToggled()));
    connect(m_buttonStart, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotStartClicked()));
    connect(m_printCommentsCheckBox, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotPrintCommentsToggled()));
    connect(m_commentsFontColor, TQ_SIGNAL(changed(const TQColor &)), this, TQ_SLOT(slotCommentsFontColorChanged()));
    connect(m_commentsBgColor, TQ_SIGNAL(changed(const TQColor &)), this, TQ_SLOT(slotCommentsBgColorChanged()));
    connect(m_useMillisecondsCheckBox, TQ_SIGNAL(toggled(bool)), TQ_SLOT(slotUseMillisecondsToggled()));
    connect(m_delaySpinBox, TQ_SIGNAL(valueChanged(int)), this, TQ_SLOT(slotDelayChanged()));
    connect(m_effectsComboBox, TQ_SIGNAL(activated(int)), this,  TQ_SLOT(slotEffectChanged()));

    connect(m_fileSrcButtonGroup, TQ_SIGNAL(clicked(int)), this, TQ_SLOT(slotSelection()));

    connect( m_ImagesFilesListBox, TQ_SIGNAL( currentChanged( TQListBoxItem * ) ),
             this, TQ_SLOT( slotImagesFilesSelected(TQListBoxItem *) ) );
    connect(m_ImagesFilesListBox, TQ_SIGNAL( addedDropItems(KURL::List) ),
            this, TQ_SLOT( slotAddDropItems(KURL::List)));
    connect( m_ImagesFilesButtonAdd, TQ_SIGNAL( clicked() ),
             this, TQ_SLOT( slotImagesFilesButtonAdd() ) );
    connect( m_ImagesFilesButtonDelete, TQ_SIGNAL( clicked() ),
             this, TQ_SLOT( slotImagesFilesButtonDelete() ) );
    connect( m_ImagesFilesButtonUp, TQ_SIGNAL( clicked() ),
             this, TQ_SLOT( slotImagesFilesButtonUp() ) );
    connect( m_ImagesFilesButtonDown, TQ_SIGNAL( clicked() ),
             this, TQ_SLOT( slotImagesFilesButtonDown() ) );
    
    connect(m_cacheCheckBox, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotCacheToggled()));
    
    m_thumbJob = 0L;
    
    // Configuration file management 

    m_config = new TDEConfig("kipirc");
    m_config->setGroup("SlideShow Settings");

    readSettings();

    slotUseMillisecondsToggled();
    
    // Comments tab management

    m_commentsFontChooser->setSampleText(
            i18n("Slideshow is part of KIPI-Plugins (http://www.kipi-plugins.org)"));

    // Host application images has comments
    if ( ! ImagesHasComments ) {
        m_printCommentsCheckBox->setEnabled(false);
        m_tabWidget->setTabEnabled(commentsTab, false);
    }
    
    m_urlList = urlList;
    
    slotSelection();
    slotEffectChanged();
}

SlideShowConfig::~SlideShowConfig()
{
    if ( m_thumbJob )   delete m_thumbJob;
    if ( m_config )     delete m_config;
}

void SlideShowConfig::loadEffectNames()
{
    m_effectsComboBox->clear();

    TQMap<TQString,TQString> effectNames = SlideShow::effectNamesI18N();
    TQStringList effects;

    TQMap<TQString,TQString>::Iterator it;
    for (it = effectNames.begin(); it != effectNames.end(); ++it)
        effects.append(it.data());

    m_effectsComboBox->insertStringList(effects);

    for (int i=0; i<m_effectsComboBox->count(); i++) {
        if (effectNames[m_effectName] == m_effectsComboBox->text(i)) {
            m_effectsComboBox->setCurrentItem(i);
            break;
        }
    }
}

void SlideShowConfig::loadEffectNamesGL()
{
    m_effectsComboBox->clear();

    TQStringList effects;
    TQMap<TQString,TQString> effectNames;
    TQMap<TQString,TQString>::Iterator it;
    
    // Load slideshowgl effects
    effectNames = SlideShowGL::effectNamesI18N();

    for (it = effectNames.begin(); it != effectNames.end(); ++it)
        effects.append(it.data());

    // Load Ken Burns effect
    effectNames = SlideShowKB::effectNamesI18N();
    for (it = effectNames.begin(); it != effectNames.end(); ++it)
      effects.append(it.data());

    // Update GUI
    
   effects.sort();
    m_effectsComboBox->insertStringList(effects);

    for (int i=0; i<m_effectsComboBox->count(); i++) {
      if (effectNames[m_effectNameGL] == m_effectsComboBox->text(i)) {
        m_effectsComboBox->setCurrentItem(i);
        break;
      }
    }
}


void SlideShowConfig::readSettings()
{
    bool  opengl;
    int   delay;
    bool  printFileName;
    bool  printProgress;
    bool  printFileComments;
    bool  loop;
    bool  shuffle;
    bool  showSelectedFilesOnly;
    bool  useMilliseconds;
    bool  enableMouseWheel;
    
    opengl                = m_config->readBoolEntry("OpenGL", false);
    delay                 = m_config->readNumEntry("Delay", 1500);
    printFileName         = m_config->readBoolEntry("Print Filename", true);
    printProgress         = m_config->readBoolEntry("Print Progress Inticator", true);
    printFileComments     = m_config->readBoolEntry("Print Comments", false);
    loop                  = m_config->readBoolEntry("Loop", false);
    shuffle               = m_config->readBoolEntry("Shuffle", false);
    showSelectedFilesOnly = m_config->readBoolEntry("Show Selected Files Only", false);
    m_effectName           = m_config->readEntry("Effect Name", "Random");
    m_effectNameGL         = m_config->readEntry("Effect Name (OpenGL)", "Random");
    
    useMilliseconds       = m_config->readBoolEntry("Use Milliseconds", false);
    enableMouseWheel      = m_config->readNumEntry("Enable Mouse Wheel", true);
    

    // Comments tab settings
    uint  commentsFontColor;
    uint  commentsBgColor;
    int   commentsLinesLength;
    
    TQFont *savedFont = new TQFont();
    savedFont->setFamily(m_config->readEntry("Comments Font Family"));
    savedFont->setPointSize(m_config->readNumEntry("Comments Font Size", 10 ));
    savedFont->setBold(m_config->readBoolEntry("Comments Font Bold", false));
    savedFont->setItalic(m_config->readBoolEntry("Comments Font Italic", false));
    savedFont->setUnderline(m_config->readBoolEntry("Comments Font Underline", false));
    savedFont->setOverline(m_config->readBoolEntry("Comments Font Overline", false));
    savedFont->setStrikeOut(m_config->readBoolEntry("Comments Font StrikeOut", false));
    savedFont->setFixedPitch(m_config->readBoolEntry("Comments Font FixedPitch", false));
    
    commentsFontColor     = m_config->readUnsignedNumEntry("Comments Font Color", 0xffffff);
    commentsBgColor       = m_config->readUnsignedNumEntry("Comments Bg Color", 0x000000);
    
    commentsLinesLength   = m_config->readNumEntry("Comments Lines Length", 72);

    // Advanced tab
    bool enableCache, kbDisableFadeInOut, kbDisableCrossFade;
    
    kbDisableFadeInOut = m_config->readBoolEntry("KB Disable FadeInOut", false);
    kbDisableCrossFade = m_config->readBoolEntry("KB Disable Crossfade", false);
    
    enableCache = m_config->readBoolEntry("Enable Cache", false);
    m_cacheSize  = m_config->readNumEntry("Cache Size", 5);
    
    
    // -- Apply Settings to widgets ------------------------------

    m_openglCheckBox->setChecked(opengl);

    m_delaySpinBox->setValue(delay);

    m_printNameCheckBox->setChecked(printFileName);
    
    m_printProgressCheckBox->setChecked(printProgress);

    m_printCommentsCheckBox->setChecked(printFileComments);

    m_loopCheckBox->setChecked(loop);

    m_shuffleCheckBox->setChecked(shuffle);
    
    m_enableMouseWheelCheckBox->setChecked(enableMouseWheel);
    m_useMillisecondsCheckBox->setChecked(useMilliseconds);

    if (showSelectedFilesOnly && m_selectedFilesButton->isEnabled() )
        m_selectedFilesButton->setChecked(true);
    else
        m_allFilesButton->setChecked(true);

    m_commentsLinesLengthSpinBox->setValue(commentsLinesLength);
    m_commentsFontColor->setColor(TQColor(commentsFontColor));
    m_commentsBgColor->setColor(TQColor(commentsBgColor));
    m_commentsFontChooser->setFont(*savedFont);
    delete savedFont;

    m_kbDisableFadeCheckBox->setChecked(kbDisableFadeInOut);
    m_kbDisableCrossfadeCheckBox->setChecked(kbDisableCrossFade);
    
    m_cacheCheckBox->setChecked(enableCache);
    
    slotOpenGLToggled();
    slotCacheToggled();
}

void SlideShowConfig::saveSettings()
{
    if (!m_config) return;

    m_config->writeEntry("OpenGL", m_openglCheckBox->isChecked());

    // Delay will be always saved as millisecond value, to keep compatibility
    if ( m_useMillisecondsCheckBox->isChecked() ) 
        m_config->writeEntry("Delay", m_delaySpinBox->value());
    else 
        m_config->writeEntry("Delay", m_delaySpinBox->value()*1000); 

    m_config->writeEntry("Print Filename", m_printNameCheckBox->isChecked());
    m_config->writeEntry("Print Progress Indicator", m_printProgressCheckBox->isChecked());
    m_config->writeEntry("Print Comments", m_printCommentsCheckBox->isChecked());
    m_config->writeEntry("Loop", m_loopCheckBox->isChecked());
    m_config->writeEntry("Shuffle", m_shuffleCheckBox->isChecked());
    m_config->writeEntry("Show Selected Files Only", m_selectedFilesButton->isChecked());

    m_config->writeEntry("Use Milliseconds", m_useMillisecondsCheckBox->isChecked()); 
    m_config->writeEntry("Enable Mouse Wheel", m_enableMouseWheelCheckBox->isChecked());

    // Comments tab settings
    TQFont* commentsFont = new TQFont(m_commentsFontChooser->font());
    m_config->writeEntry("Comments Font Family", commentsFont->family());
    m_config->writeEntry("Comments Font Size", commentsFont->pointSize());
    m_config->writeEntry("Comments Font Bold", commentsFont->bold());
    m_config->writeEntry("Comments Font Italic", commentsFont->italic());
    m_config->writeEntry("Comments Font Underline", commentsFont->underline());
    m_config->writeEntry("Comments Font Overline", commentsFont->overline());
    m_config->writeEntry("Comments Font StrikeOut", commentsFont->strikeOut());
    m_config->writeEntry("Comments Font FixedPitch", commentsFont->fixedPitch());
    delete commentsFont;
    
    TQColor* fontColor = new TQColor(m_commentsFontColor->color());
    uint commentsFontColorRGB = fontColor->rgb(); 
    delete fontColor;
    m_config->writeEntry("Comments Font Color", commentsFontColorRGB);

    TQColor* bgColor = new TQColor(m_commentsBgColor->color());
    uint commentsBgColorRGB = bgColor->rgb();
    delete bgColor;
    m_config->writeEntry("Comments Bg Color", commentsBgColorRGB);

    m_config->writeEntry("Comments Lines Length", m_commentsLinesLengthSpinBox->value());
    
    if (!m_openglCheckBox->isChecked()) {

        TQString effect;
        TQMap<TQString,TQString> effectNames = SlideShow::effectNamesI18N();
        TQMap<TQString,TQString>::Iterator it;

        for (it = effectNames.begin(); it != effectNames.end(); ++it) {
            if (it.data() == m_effectsComboBox->currentText()) {
                effect = it.key();
                break;
            }
        }

        m_config->writeEntry("Effect Name", effect);

    }
    else 
    {
      TQMap<TQString,TQString> effects;
      TQMap<TQString,TQString> effectNames;
      TQMap<TQString,TQString>::Iterator it;
    
      // Load slideshowgl effects
      effectNames = SlideShowGL::effectNamesI18N();

      for (it = effectNames.begin(); it != effectNames.end(); ++it)
        effects.insert(it.key(),it.data());

      // Load Ken Burns effect
      effectNames = SlideShowKB::effectNamesI18N();
      for (it = effectNames.begin(); it != effectNames.end(); ++it)
        effects.insert(it.key(),it.data());

        TQString effect;

        for (it = effects.begin(); it != effects.end(); ++it) {
            if ( it.data() == m_effectsComboBox->currentText()) {
                effect = it.key();
                break;
            }
        }

        m_config->writeEntry("Effect Name (OpenGL)", effect);
    }

    // Advanced settings
    m_config->writeEntry("KB Disable FadeInOut", m_kbDisableFadeCheckBox->isChecked());
    m_config->writeEntry("KB Disable Crossfade", m_kbDisableCrossfadeCheckBox->isChecked());
    
    m_config->writeEntry("Enable Cache", m_cacheCheckBox->isChecked());
    m_config->writeEntry("Cache Size", m_cacheSizeSpinBox->value());
    
    m_config->sync();
}

void SlideShowConfig::addItems(const KURL::List& fileList)
{
    if (fileList.isEmpty()) return;
    KURL::List Files = fileList;

    for ( KURL::List::Iterator it = Files.begin() ; it != Files.end() ; ++it )
    {
        KURL currentFile = *it;

        TQFileInfo fi(currentFile.path());
        TQString Temp = fi.dirPath();
        TQString albumName = Temp.section('/', -1);

        KIPI::ImageInfo info = m_interface->info(currentFile);
        TQString comments = info.description();

        ImageItem *item = new ImageItem( m_ImagesFilesListBox,
                                         currentFile.path().section('/', -1 ),   // File name with extension.
                                         comments,                               // Image comments.
                                         currentFile.path().section('/', 0, -1), // Complete path with file name.
                                         albumName                               // Album name.
                                       );

        item->setName( currentFile.path().section('/', -1) );
    }

    ShowNumberImages( m_ImagesFilesListBox->count() );
    m_ImagesFilesListBox->setCurrentItem( m_ImagesFilesListBox->count()-1) ;
    slotImagesFilesSelected(m_ImagesFilesListBox->item(m_ImagesFilesListBox->currentItem()));
    m_ImagesFilesListBox->centerCurrentItem();
}

void SlideShowConfig::slotCommentsBgColorChanged()
{
    m_commentsFontChooser->setBackgroundColor(m_commentsBgColor->color());
}

void SlideShowConfig::slotCommentsFontColorChanged()
{
    m_commentsFontChooser->setColor(m_commentsFontColor->color());
}

void SlideShowConfig::slotPrintCommentsToggled()
{
    m_tabWidget->setTabEnabled(commentsTab, m_printCommentsCheckBox->isChecked());
}

void SlideShowConfig::slotUseMillisecondsToggled()
{

    int delayValue = m_delaySpinBox->value();
    
    m_delaySpinBox->setValue(0);
    
    if ( m_useMillisecondsCheckBox -> isChecked() ) {
        m_delayLabel->setText(TQString("Delay between images (ms):"));

        m_delaySpinBox->setMinValue(m_delayMsMinValue);
        m_delaySpinBox->setMaxValue(m_delayMsMaxValue);
        m_delaySpinBox->setLineStep(m_delayMsLineStep); 
        
        m_delaySpinBox->setValue(delayValue*1000);
    }
    else { 
        m_delayLabel->setText(TQString("Delay between images  (s):"));
        
        m_delaySpinBox->setMinValue(m_delayMsMinValue/1000);
        m_delaySpinBox->setMaxValue(m_delayMsMaxValue/100);
        m_delaySpinBox->setLineStep(m_delayMsLineStep/10); 
        
        m_delaySpinBox->setValue(delayValue/1000);
    }
}

void SlideShowConfig::slotEffectChanged()
{
  bool isKB = m_effectsComboBox->currentText() == i18n("Ken Burns");
  
  m_printNameCheckBox->setEnabled(!isKB);
  m_printProgressCheckBox->setEnabled(!isKB);
  m_printCommentsCheckBox->setEnabled(!isKB);
  
  m_cacheButtonGroup->setEnabled(!isKB);
}

void SlideShowConfig::slotCacheToggled()
{
  bool isEnabled = m_cacheCheckBox->isChecked();
  
  m_cacheSizeLabel1->setEnabled(isEnabled);
  m_cacheSizeLabel2->setEnabled(isEnabled);
  m_cacheSizeSpinBox->setEnabled(isEnabled);
}

void SlideShowConfig::slotOpenGLToggled()
{
    if (m_openglCheckBox->isChecked()) {
        loadEffectNamesGL();
    }
    else {
        loadEffectNames();
    }
    
    ShowNumberImages( m_ImagesFilesListBox->count() );
    
//    slotEffectChanged();
}

void SlideShowConfig::slotDelayChanged()
{
    ShowNumberImages( m_ImagesFilesListBox->count() );
}

void SlideShowConfig::slotSelection()
{
    KURL::List urlList;
    if (m_selectedFilesButton->isChecked())
    {
        urlList = m_interface->currentSelection().images();
        
        m_ImagesFilesButtonAdd->setEnabled(false);
        m_ImagesFilesButtonDelete->setEnabled(false);
        m_ImagesFilesButtonUp->setEnabled(false);
        m_ImagesFilesButtonDown->setEnabled(false);
    }   
    else
        if (m_allFilesButton->isChecked())
        {
            KURL currentPath = m_interface->currentAlbum().path();
            TQValueList<KIPI::ImageCollection> albumList;
            albumList = m_interface->allAlbums();
            TQValueList<KIPI::ImageCollection>::iterator it;
    
            urlList = m_interface->currentAlbum().images();
            for ( it = albumList.begin(); it != albumList.end(); ++it )
                if (currentPath.isParentOf((*it).path()) && !((*it).path() == currentPath))
                    urlList += (*it).images();
            
            m_ImagesFilesButtonAdd->setEnabled(false);
            m_ImagesFilesButtonDelete->setEnabled(false);
            m_ImagesFilesButtonUp->setEnabled(false);
            m_ImagesFilesButtonDown->setEnabled(false);
        }
     
    if ( m_customButton->isChecked() )    // Custom selected
    {
        m_ImagesFilesButtonAdd->setEnabled(true);
        m_ImagesFilesButtonDelete->setEnabled(true);
        m_ImagesFilesButtonUp->setEnabled(true);
        m_ImagesFilesButtonDown->setEnabled(true);
    }
    else
    {
        if (!urlList.isEmpty()) 
        {
            m_ImagesFilesListBox->clear();
            addItems(urlList);
        }
    }
}

void SlideShowConfig::slotImagesFilesSelected( TQListBoxItem *item )
{
    
    if ( !item || m_ImagesFilesListBox->count() == 0 )
    {
        m_label7->setText("");
        m_ImageLabel->clear();
        return;
    }

    ImageItem *pitem = static_cast<ImageItem*>( item );

    if ( !pitem ) return;

    KURL url;
    url.setPath(pitem->path());

    m_ImageLabel->clear();

    if ( m_thumbJob ) delete m_thumbJob;

    m_thumbJob = TDEIO::filePreview( url, m_ImageLabel->width() );

    connect(m_thumbJob, TQ_SIGNAL(gotPreview(const KFileItem*, const TQPixmap&)),
            TQ_SLOT(slotGotPreview(const KFileItem*, const TQPixmap&)));
    connect(m_thumbJob, TQ_SIGNAL(failed(const KFileItem*)),
            TQ_SLOT(slotFailedPreview(const KFileItem*)));

    int index = m_ImagesFilesListBox->index ( item );
    m_label7->setText(i18n("Image no. %1").arg(index + 1));
}

void SlideShowConfig::slotAddDropItems(KURL::List filesUrl)
{
    addItems(filesUrl);
}

void SlideShowConfig::slotImagesFilesButtonAdd( void )
{
    KURL::List ImageFilesList =
            KIPI::ImageDialog::getImageURLs( this, m_interface );
    if ( !ImageFilesList.isEmpty() )
        addItems( ImageFilesList );
}

void SlideShowConfig::slotImagesFilesButtonDelete( void )
{
    for (uint i = 0 ; i < m_ImagesFilesListBox->count() ; ++i)
    {
        if (m_ImagesFilesListBox->isSelected(i))
        {
            m_ImagesFilesListBox->removeItem(i);
            m_ImagesFilesListBox->setCurrentItem(i);
            --i;
        }
    }

    m_ImagesFilesListBox->setSelected(m_ImagesFilesListBox->item(m_ImagesFilesListBox->currentItem()), true);
    slotImagesFilesSelected(m_ImagesFilesListBox->item(m_ImagesFilesListBox->currentItem()));
    ShowNumberImages( m_ImagesFilesListBox->count() );
}

void SlideShowConfig::slotImagesFilesButtonUp( void )
{
    int Cpt = 0;

    for (uint i = 0 ; i < m_ImagesFilesListBox->count() ; ++i)
        if (m_ImagesFilesListBox->isSelected(i))
            ++Cpt;

    if  (Cpt == 0)
        return;

    if  (Cpt > 1)
    {
        KMessageBox::error(this, i18n("You can only move up one image file at once."));
        return;
    }

    unsigned int Index = m_ImagesFilesListBox->currentItem();

    if (Index == 0)
        return;

    ImageItem *pitem = static_cast<ImageItem*>( m_ImagesFilesListBox->item(Index) );
    TQString path(pitem->path());
    TQString comment(pitem->comments());
    TQString name(pitem->name());
    TQString album(pitem->album());
    m_ImagesFilesListBox->removeItem(Index);
    ImageItem *item = new ImageItem( 0, name, comment, path, album );
    item->setName( name );
    m_ImagesFilesListBox->insertItem(item, Index-1);
    m_ImagesFilesListBox->setSelected(Index-1, true);
    m_ImagesFilesListBox->setCurrentItem(Index-1);
}

void SlideShowConfig::slotImagesFilesButtonDown( void )
{
    int Cpt = 0;

    for (uint i = 0 ; i < m_ImagesFilesListBox->count() ; ++i)
        if (m_ImagesFilesListBox->isSelected(i))
            ++Cpt;

    if (Cpt == 0)
        return;

    if (Cpt > 1)
    {
        KMessageBox::error(this, i18n("You can only move down one image file at once."));
        return;
    }

    unsigned int Index = m_ImagesFilesListBox->currentItem();

    if (Index == m_ImagesFilesListBox->count())
        return;

    ImageItem *pitem = static_cast<ImageItem*>( m_ImagesFilesListBox->item(Index) );
    TQString path(pitem->path());
    TQString comment(pitem->comments());
    TQString name(pitem->name());
    TQString album(pitem->name());
    m_ImagesFilesListBox->removeItem(Index);
    ImageItem *item = new ImageItem( 0, name, comment, path, album );
    item->setName( name );
    m_ImagesFilesListBox->insertItem(item, Index+1);
    m_ImagesFilesListBox->setSelected(Index+1, true);
    m_ImagesFilesListBox->setCurrentItem(Index+1);
}

void SlideShowConfig::ShowNumberImages( int Number )
{
    TQTime TotalDuration (0, 0, 0);
    
    int TransitionDuration = 2000;
    
    if ( m_openglCheckBox->isChecked() )
        TransitionDuration += 500;
    
    if ( m_useMillisecondsCheckBox->isChecked() )
        TotalDuration = TotalDuration.addMSecs(Number * m_delaySpinBox->text().toInt());
    else
        TotalDuration = TotalDuration.addSecs(Number * m_delaySpinBox->text().toInt());
    
    TotalDuration = TotalDuration.addMSecs((Number-1)*TransitionDuration);

    if ( Number < 2)
        m_label6->setText(i18n("%1 image [%2]").arg(Number).arg(TotalDuration.toString()));
    else
        m_label6->setText(i18n("%1 images [%2]").arg(Number).arg(TotalDuration.toString()));
}

void SlideShowConfig::slotGotPreview(const KFileItem*, const TQPixmap &pixmap)
{
    m_ImageLabel->setPixmap(pixmap);
    m_thumbJob = 0L;
}

void SlideShowConfig::slotFailedPreview(const KFileItem*)
{
    m_thumbJob = 0L;
}

void SlideShowConfig::SlotPortfolioDurationChanged ( int )
{
    ShowNumberImages( m_ImagesFilesListBox->count() );
}

void SlideShowConfig::slotStartClicked()
{
    saveSettings();

    for (uint i=0 ; i < m_ImagesFilesListBox->count() ; ++i)
    {
        ImageItem *pitem = static_cast<ImageItem*>( m_ImagesFilesListBox->item(i) );
        if (!TQFile::exists(pitem->path()))
        {
            KMessageBox::error(this,
                               i18n("Cannot access to file %1, please check the path is right.").arg(pitem->path()));
            return;
        }
        m_urlList->append(pitem->path());                              // Input images files.
    }
    
    emit buttonStartClicked();
}


void SlideShowConfig::slotHelp()
{
    tdeApp->invokeHelp("slideshow",
                                             "kipi-plugins");
}

}  // NameSpace KIPISlideShowPlugin
