/* ============================================================
 *
 * This file is a part of kipi-plugins project
 * http://www.kipi-plugins.org
 *
 * Date        : 2008-05-21
 * Description : a kipi plugin to export images to Flickr web service
 *
 * Copyright (C) 2008 by Gilles Caulier <caulier dot gilles at gmail dot 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, 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.
 *
 * ============================================================ */

#define ICONSIZE 64

// QT includes.

#include <tqpushbutton.h>
#include <tqpainter.h>
#include <tqfileinfo.h>
#include <tqlayout.h>
#include <tqwhatsthis.h>
#include <tqdragobject.h>
#include <tqimage.h>

// KDE includes.

#include <tdelocale.h>
#include <kdialog.h>
#include <knuminput.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <tdeio/previewjob.h>

// Libkipi includes.

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

// Local includes.

#include "imageslist.h"
#include "imageslist.moc"

namespace KIPIFlickrExportPlugin
{

ImagesListViewItem::ImagesListViewItem(TQListView *view, const KURL& url)
                  : TQListViewItem(view)
{
    setThumb(SmallIcon("file_broken", ICONSIZE, TDEIcon::DisabledState));
    setUrl(url);
}

ImagesListViewItem::~ImagesListViewItem()
{
}

void ImagesListViewItem::setUrl(const KURL& url)
{
    m_url = url;
    setText(1, m_url.fileName());
}

KURL ImagesListViewItem::url() const
{
    return m_url;
}

void ImagesListViewItem::setThumb(const TQPixmap& pix) 
{ 
    TQPixmap pixmap(ICONSIZE+2, ICONSIZE+2);
    pixmap.fill(TQt::color0);
    TQPainter p(&pixmap);
    p.drawPixmap((pixmap.width()/2) - (pix.width()/2), (pixmap.height()/2) - (pix.height()/2), pix);
    setPixmap(0, pixmap); 
}

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

ImagesListView::ImagesListView(TQWidget *parent)
              : TQListView(parent)
{
    addColumn(i18n("Thumbnail"));
    addColumn(i18n("File Name"));
    TQWhatsThis::add(this, i18n("<p>This is the list of images to upload on your Flickr account."));
    setAcceptDrops(true);
    setResizeMode(TQListView::AllColumns);
    setAllColumnsShowFocus(true);
    setSorting(-1);
    setSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Expanding);
    setSelectionMode(TQListView::Extended);
}

ImagesListView::~ImagesListView()
{
}

void ImagesListView::dragEnterEvent(TQDragEnterEvent *e)
{
    e->accept(TQUriDrag::canDecode(e));
}

void ImagesListView::dropEvent(TQDropEvent *e)
{
    TQStrList   strList;
    KURL::List urls;

    if (!TQUriDrag::decode(e, strList)) 
        return;

    TQStrList stringList;
    TQStrListIterator it(strList);
    char *str;

    while ((str = it.current()) != 0)
    {
        TQString filePath = TQUriDrag::uriToLocalFile(str);
        TQFileInfo fileInfo(filePath);

        if (fileInfo.isFile() && fileInfo.exists())
            urls.append(fileInfo.filePath());

        ++it;
    }

    if (!urls.isEmpty())
       emit signalDropedItems(urls);
}

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

class ImagesPagePriv
{
public:

    ImagesPagePriv()
    {
        listView     = 0;
        addButton    = 0;
        removeButton = 0;
        iface        = 0;
    }

    TQPushButton     *addButton;
    TQPushButton     *removeButton;

    ImagesListView  *listView;

    KIPI::Interface *iface;
};

ImagesList::ImagesList(TQWidget* parent, KIPI::Interface *iface)
          : TQWidget(parent)
{
    d = new ImagesPagePriv;
    d->iface = iface;

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

    TQGridLayout* grid = new TQGridLayout(this, 2, 3);
    d->listView       = new ImagesListView(this);

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

    d->addButton    = new TQPushButton(this);
    d->removeButton = new TQPushButton(this);
    d->addButton->setText(i18n("&Add"));
    d->addButton->setIconSet(SmallIcon("add"));
    d->removeButton->setText(i18n("&Remove"));
    d->removeButton->setIconSet(SmallIcon("remove"));

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

    grid->addMultiCellWidget(d->listView,     0, 2, 0, 2);
    grid->addMultiCellWidget(d->addButton,    0, 0, 3, 3);
    grid->addMultiCellWidget(d->removeButton, 1, 1, 3, 3);
    grid->setColStretch(0, 10);
    grid->setRowStretch(2, 10);
    grid->setMargin(KDialog::spacingHint());
    grid->setSpacing(KDialog::spacingHint());

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

    connect(d->addButton, TQT_SIGNAL(clicked()),
            this, TQT_SLOT(slotAddItems()));

    connect(d->removeButton, TQT_SIGNAL(clicked()),
            this, TQT_SLOT(slotRemoveItems()));

    connect(d->listView, TQT_SIGNAL(signalDropedItems(const KURL::List&)),
            this, TQT_SLOT(slotAddImages(const KURL::List&)));

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

    KIPI::ImageCollection images = d->iface->currentSelection();

    if (images.isValid())
        slotAddImages(images.images());
}

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

void ImagesList::slotAddImages(const KURL::List& list)
{
    if (list.count() == 0) return;

    KURL::List urls;

    for(KURL::List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        KURL imageUrl = *it;

        // Check if the new item already exist in the list.

        bool find = false;

        TQListViewItemIterator it2(d->listView);
        while (it2.current())
        {
            ImagesListViewItem* item = dynamic_cast<ImagesListViewItem*>(*it2);

            if (item->url() == imageUrl)
                find = true;

            ++it2;
        }

        if (!find)
        {
            new ImagesListViewItem(d->listView, imageUrl);
            urls.append(imageUrl);
        }
    }

    emit signalImageListChanged(imageUrls().isEmpty());

    TDEIO::PreviewJob *thumbnailJob = TDEIO::filePreview(urls, ICONSIZE);

    connect(thumbnailJob, TQT_SIGNAL(gotPreview(const KFileItem*, const TQPixmap&)),
            this, TQT_SLOT(slotGotThumbnail(const KFileItem*, const TQPixmap&)));
}

void ImagesList::slotGotThumbnail(const KFileItem *item, const TQPixmap& pix)
{
    TQListViewItemIterator it2(d->listView);

    while (it2.current())
    {
        ImagesListViewItem *selItem = dynamic_cast<ImagesListViewItem*>(*it2);
        if (selItem->url() == item->url())
        {
            selItem->setPixmap(0, pix);
        }
        ++it2;
    }
}

void ImagesList::slotAddItems()
{
    KURL::List urls = KIPI::ImageDialog::getImageURLs(this, d->iface);
    if (!urls.isEmpty())
        slotAddImages(urls);

    emit signalImageListChanged(imageUrls().isEmpty());
}

void ImagesList::slotRemoveItems()
{
    bool find;
    do
    {
        find = false;
        TQListViewItemIterator it2(d->listView);
        while (it2.current())
        {
            ImagesListViewItem* item = dynamic_cast<ImagesListViewItem*>(*it2);
            if (item->isSelected())
            {
                delete item;
                find = true;
                break;
            }
            ++it2;
        }
    }
    while(find);

    emit signalImageListChanged(imageUrls().isEmpty());
}

void ImagesList::removeItemByUrl(const KURL& url)
{
    bool find;
    do
    {
        find = false;
        TQListViewItemIterator it2(d->listView);
        while (it2.current())
        {
            ImagesListViewItem* item = dynamic_cast<ImagesListViewItem*>(*it2);
            if (item->url() == url)
            {
                delete item;
                find = true;
                break;
            }
            ++it2;
        }
    }
    while(find);

    emit signalImageListChanged(imageUrls().isEmpty());
}

KURL::List ImagesList::imageUrls() const
{
    KURL::List list;
    TQListViewItemIterator it2(d->listView);
    while (it2.current())
    {
        ImagesListViewItem* item = dynamic_cast<ImagesListViewItem*>(*it2);
        list.append(item->url());
        ++it2;
    }
    return list;
}

}  // namespace KIPIFlickrExportPlugin
