/* ============================================================
 * File   : imagedialog.cpp
 * Authors: KIPI team developers (see AUTHORS files for details)
 *      
 * Date   : 2004-05
 * Description : an image files selector dialog.
 *
 * Copyright 2004 by the KIPI team
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Library 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 Library General Public License for more details.
 *
 * ============================================================ */
 
// TQt includes.
 
#include <tqguardedptr.h>
#include <tqlabel.h>
#include <tqsplitter.h>
#include <tqlayout.h>
#include <tqframe.h>
#include <tqpushbutton.h>
#include <tqtimer.h>

// KDE includes.

#include <kdebug.h>
#include <tdelistview.h>
#include <tdelocale.h>
#include <kstandarddirs.h>
#include <tdeio/previewjob.h>
#include <tdeapplication.h>
#include <tdeaboutdata.h>
#include <khelpmenu.h>
#include <kiconloader.h>
#include <tdepopupmenu.h>

// Include files for libKipi.

#include "libkipi/version.h"

// Local includes.

#include "imagedialog.h"

const int PREVIEW_SIZE = 128;

namespace KIPI
{

struct AlbumLVI : public TDEListViewItem {
    AlbumLVI(TDEListView* parent, const KIPI::ImageCollection& album)
    : TDEListViewItem(parent, album.name())
    , _album(album) {}

    const KIPI::ImageCollection& _album;
};


struct ImageLVI : public TDEListViewItem {
    ImageLVI(TDEListView* parent, const KURL& url)
    : TDEListViewItem(parent, url.fileName()), _url(url) {}

    KURL _url;
};


struct ImageDialog::Private {
    KURL _url;
    KURL::List _urls;
    KIPI::Interface* _interface;
    TDEListView* _albumList;
    TDEListView* _imageList;
    TQLabel* _preview;
    TQValueList<ImageCollection> _albums;
    bool _singleSelection;
};


ImageDialog::ImageDialog(TQWidget* parent, KIPI::Interface* interface,
                         bool singleSelection)
           : KDialogBase(KDialogBase::Plain, i18n("Select Image From Album"), Help|Ok|Cancel,
                         Ok, parent, "album-dialog", true, true)                         
{
    d = new Private;
    d->_interface=interface;
    d->_singleSelection = singleSelection;
        
    TQWidget* box = plainPage();
    TQVBoxLayout *dvlay = new TQVBoxLayout( box, 6 );

    //---------------------------------------------
   
    TQFrame *headerFrame = new TQFrame( box );
    headerFrame->setFrameStyle(TQFrame::Panel|TQFrame::Sunken);
    TQHBoxLayout* layout = new TQHBoxLayout( headerFrame );
    layout->setMargin( 2 ); // to make sure the frame gets displayed
    layout->setSpacing( 0 );
    TQLabel *pixmapLabelLeft = new TQLabel( headerFrame, "pixmapLabelLeft" );
    pixmapLabelLeft->setScaledContents( false );
    layout->addWidget( pixmapLabelLeft );
    TQLabel *labelTitle = new TQLabel( i18n("Select Image From Album"), headerFrame, "labelTitle" );
    layout->addWidget( labelTitle );
    layout->setStretchFactor( labelTitle, 1 );
    dvlay->addWidget( headerFrame );
    
    TQString directory;
    TDEGlobal::dirs()->addResourceType("kipi_banner_left", TDEGlobal::dirs()->kde_default("data") + "kipi/data");
    directory = TDEGlobal::dirs()->findResourceDir("kipi_banner_left", "banner_left.png");
    
    pixmapLabelLeft->setPaletteBackgroundColor( TQColor(201, 208, 255) );
    pixmapLabelLeft->setPixmap( TQPixmap( directory + "banner_left.png" ) );
    labelTitle->setPaletteBackgroundColor( TQColor(201, 208, 255) );

    //---------------------------------------------
    
    // About data and help button.
    
    TDEAboutData* about = new TDEAboutData("kipiplugins",
                                       I18N_NOOP("Image selector dialog"), 
                                       kipi_version,
                                       I18N_NOOP("A Kipi dialog for image selection"),
                                       TDEAboutData::License_GPL,
                                       "(c) 2004,2005, Kipi development team", 
                                       0,
                                       "http://extragear.kde.org/apps/kipi");
    
    TQPushButton *helpButton = actionButton( Help );
    KHelpMenu* helpMenu = new KHelpMenu(this, about, false);
    helpMenu->menu()->removeItemAt(0);
    helpMenu->menu()->insertItem(i18n("Kipi Plugins Handbooks"), this, TQ_SLOT(slotHelp()), 0, -1, 0);
    helpButton->setPopup( helpMenu->menu() );

    //---------------------------------------------

    TQSplitter* splitter = new TQSplitter(box);
        
    d->_albumList=new TDEListView(splitter);
    d->_albumList->addColumn(i18n("Album Name"));
    d->_albumList->setMinimumWidth(200);
    d->_albumList->setResizeMode(TQListView::LastColumn);

    d->_imageList=new TDEListView(splitter);
    d->_imageList->addColumn(i18n("Image Name"));
    d->_imageList->setMinimumWidth(200);
    d->_imageList->setSelectionMode(singleSelection ? TQListView::Single :
                                    TQListView::Extended);
    d->_imageList->setResizeMode(TQListView::LastColumn);
    
    d->_preview=new TQLabel(splitter);
    d->_preview->setAlignment(AlignHCenter | AlignVCenter | WordBreak);
    d->_preview->setFixedWidth(PREVIEW_SIZE);
    d->_preview->setText(i18n("No image selected"));

    dvlay->addWidget( splitter );

    d->_albums=d->_interface->allAlbums();
    TQValueList<ImageCollection>::ConstIterator it=d->_albums.begin();
    
    for(; it!=d->_albums.end(); ++it) {
        new AlbumLVI(d->_albumList, *it);
    }
    TQTimer::singleShot(0, this, TQ_SLOT(slotInitialShow()));

    connect(d->_albumList, TQ_SIGNAL(selectionChanged(TQListViewItem*)),
            this, TQ_SLOT(fillImageList(TQListViewItem*)) );

    if (singleSelection)
        connect(d->_imageList, TQ_SIGNAL(selectionChanged(TQListViewItem*)),
                this, TQ_SLOT(slotImageSelected(TQListViewItem*)) );
    else
        connect(d->_imageList, TQ_SIGNAL(selectionChanged()),
                this, TQ_SLOT(slotImagesSelected()));

    enableButtonOK(false);
}


ImageDialog::~ImageDialog() {
    delete d;
}


KURL ImageDialog::url() const {
    return d->_url;
}

KURL::List ImageDialog::urls() const
{
    return d->_urls;    
}

KURL ImageDialog::getImageURL(TQWidget* parent, KIPI::Interface* interface) {
    ImageDialog dlg(parent, interface, true);
    if (dlg.exec() == TQDialog::Accepted) {
        return dlg.url();
    } else {
        return KURL();
    }
}

KURL::List ImageDialog::getImageURLs(TQWidget* parent, Interface* interface)
{
    ImageDialog dlg(parent, interface, false);
    if (dlg.exec() == TQDialog::Accepted)
        return dlg.urls();
    else
    {
        KURL::List urls;
        return urls;
    }
}


void ImageDialog::fillImageList(TQListViewItem* item) {
    d->_imageList->clear();
    if (!item) return;

    const KIPI::ImageCollection& album=static_cast<AlbumLVI*>(item)->_album;
    KURL::List images=album.images();

    KURL::List::ConstIterator it=images.begin();
    for (;it!=images.end(); ++it) {
        new ImageLVI(d->_imageList, *it);
    }
}


void ImageDialog::slotImageSelected(TQListViewItem* item) {
    if (!item) {
        enableButtonOK(false);
        d->_preview->setText(i18n("No image selected"));
        d->_url=KURL();
        return;
    }
    enableButtonOK(true);
    d->_url=static_cast<ImageLVI*>(item)->_url;
    d->_preview->clear();

    TDEIO::PreviewJob* thumbJob = TDEIO::filePreview(d->_url, PREVIEW_SIZE);
    connect( thumbJob, TQ_SIGNAL(gotPreview(const KFileItem*, const TQPixmap&)),
             TQ_SLOT(slotGotPreview(const KFileItem* , const TQPixmap&)));
}

void ImageDialog::slotImagesSelected()
{
    d->_url = KURL();
    d->_urls.clear();
    d->_preview->clear();

    TQListViewItem* selectedItem = 0;
    TQListViewItem* listItem = d->_imageList->firstChild();
    while (listItem)
    {
        if (listItem->isSelected())
        {
            selectedItem = listItem;
            d->_urls.append(static_cast<ImageLVI*>(listItem)->_url);
        }
        listItem = listItem->nextSibling();
    }

    if (!selectedItem)
    {
        enableButtonOK(false);
        d->_preview->setText(i18n("No images selected"));
        d->_url=KURL();
        d->_urls.clear();
        return;
    }

    enableButtonOK(true);
    
    if (d->_urls.count() == 1)
    {
        d->_url = d->_urls.first();

        TDEIO::PreviewJob* thumbJob = TDEIO::filePreview(d->_url, PREVIEW_SIZE);
        connect( thumbJob, TQ_SIGNAL(gotPreview(const KFileItem*, const TQPixmap&)),
                 TQ_SLOT(slotGotPreview(const KFileItem* , const TQPixmap&)));
    }
    else
    {
        d->_url = d->_urls.first();
        d->_preview->setText(i18n("1 image selected", "%n images selected", d->_urls.count()));
    }
}

void ImageDialog::slotGotPreview(const KFileItem*, const TQPixmap& pix) {

    d->_preview->setPixmap(pix);
}

void ImageDialog::slotHelp( void )
{
    TDEApplication::kApplication()->invokeHelp("", "kipi-plugins");
}

void ImageDialog::slotInitialShow()
{
    ImageCollection current = d->_interface->currentAlbum();

    TQListViewItemIterator it( d->_albumList );
    while ( it.current() )
    {
        AlbumLVI* lvi = static_cast<AlbumLVI*>( it.current() );
        if ( lvi->_album == current )
        {
            d->_albumList->ensureItemVisible( lvi );
            d->_albumList->setSelected( lvi, true );
            break;
        }
        ++it;
    }
}

} // namespace KIPI

#include "imagedialog.moc"
