#include "filelist.h"
#include <kurl.h>
#include <kmimetype.h>
#include <kpopupmenu.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <qapplication.h>
#include <qclipboard.h>
#include <qfileinfo.h>
#include <qdragobject.h>
#include <qpainter.h>
#include <qstyle.h>

KIFFileList::KIFFileList(QWidget *parent, const char *name)
    : KIFDndListBox(parent, name)
{
    setSelectionMode(QListBox::Extended);
    setAcceptDrops(true);
    connect(this, SIGNAL(rightButtonClicked(QListBoxItem *, const QPoint &)),
            SLOT(slotRightButton(QListBoxItem *, const QPoint &)));
}

void KIFFileList::slotAppend(const QString &filename)
{
    if(!findItem(filename))
        insertItem(filename);
}

void KIFFileList::slotAppendAndSet(const QString &filename)
{
    if(!findItem(filename))
        insertItem(filename);
    QListBoxItem *item = findItem(filename);
    clearSelection();
    setCurrentItem(item);
    setSelected(item, true);
}

void KIFFileList::slotNextInList()
{
    if(count() > 1){
        unsigned int current = currentItem();
        if(current+1 < count()){
            clearSelection();
            setCurrentItem(current+1);
            setSelected(current+1, true);
            emit selected(item(current+1));
        }
    }

}

void KIFFileList::slotPrevInList()
{
    if(count() > 1){
        int current = currentItem();
        if(current-1 >= 0){
            clearSelection();
            setCurrentItem(current-1);
            setSelected(current-1, true);
            emit selected(item(current-1));
        }
    }
}

void KIFFileList::slotRightButton(QListBoxItem *i, const QPoint &pos)
{
    KPopupMenu *mnu = new KPopupMenu;
    mnu->insertTitle(i18n("FileList Options"));
    mnu->insertItem(BarIcon("pencil", KIcon::SizeSmall),
                    i18n("Edit Image..."), 1);
    mnu->insertSeparator();
    mnu->insertItem(BarIcon("editcopy", KIcon::SizeSmall),
                    i18n("Copy file location"), 3);
    mnu->insertItem(BarIcon("editcopy", KIcon::SizeSmall),
                    i18n("Copy filename only"), 4);
    mnu->insertSeparator();
    mnu->insertItem(BarIcon("filesave", KIcon::SizeSmall),
                    i18n("Save FileList..."), 6);
    mnu->insertItem(BarIcon("edittrash", KIcon::SizeSmall),
                    i18n("Remove from FileList"), 7);
    mnu->insertItem(BarIcon("edittrash", KIcon::SizeSmall),
                    i18n("Clear FileList"), 8);
    if(!i){
        mnu->setItemEnabled(1, false);
        mnu->setItemEnabled(3, false);
        mnu->setItemEnabled(4, false);
        mnu->setItemEnabled(7, false);
    }
    int id = mnu->exec(pos);
    delete mnu;
    if(id == 1){
        // Edit Image
        emit editImage(i->text());
    }
    else if(id == 3){
        // Copy file location
        QFileInfo fi(i->text());
        QApplication::clipboard()->setText(fi.absFilePath());
    }
    else if(id == 4){
        // Copy Filename Only
        QFileInfo fi(i->text());
        QApplication::clipboard()->setText(fi.fileName());
    }
    else if(id == 6){
        // Save
        emit save();
    }
    else if(id == 7){
        // Remove
        QStringList fileList;
        unsigned int i;
        for(i=0; i < count(); ++i){
            if(isSelected(i))
                fileList.append(text(i));
        }
        if(!fileList.isEmpty()){
            for(QStringList::Iterator it = fileList.begin(); it != fileList.end(); ++it)
                delete findItem(*it);
        }
        /* buggy
        int i;
        QListBoxItem *ptr;
        for(i=0; i < count(); ++i){
            ptr = item(i);
            if(ptr->selected())
                delete ptr;
        }*/
    }
    else if(id == 8){
        // Clear
        clear();
    }
}

void KIFFileList::mousePressEvent(QMouseEvent *ev)
{
    // Do nothing on right click, just emit signal. This avoids annoying
    // unselecting when using the right-click menu
    if(ev->button() == RightButton){
        QListBoxItem *i = itemAt(ev->pos());
        emit rightButtonClicked(i, ev->globalPos());
    }
    else
        QListBox::mousePressEvent(ev);
}

void KIFFileList::paintCell(QPainter *p, int row, int col)
{
    const QColorGroup & g = colorGroup();
    QListBoxItem * i = item( col*numRows()+row );
    p->save();
    if (i->selected()) {
        p->fillRect( 0, 0, maxItemWidth(), i->height(this), g.brush( QColorGroup::Highlight ) );
        p->setPen( g.highlightedText() );
        p->setBackgroundColor( g.highlight() );
    }
    else {
        p->fillRect( 0, 0, maxItemWidth(), i->height(this),
                     row & 0x01 ? g.base().dark(110) : g.base());
    }

    if(i->pixmap())
        p->drawPixmap(3, 0, *i->pixmap());
    if (!i->text().isEmpty()){
        int pixW = i->pixmap() ? i->pixmap()->width() : 0;
        int pixH = i->pixmap() ? i->pixmap()->height() : 0;

        QFontMetrics fm = p->fontMetrics();
        int yPos;                       // vertical text position
        if (pixH < fm.height())
            yPos = fm.ascent() + fm.leading()/2;
        else
            yPos = pixH/2 - fm.height()/2 + fm.ascent();
        p->drawText(pixW + 5, yPos, i->text());
    }

    if(item(currentItem()) == i && hasFocus()){
        style().drawPrimitive( QStyle::PE_FocusRect, p,
                               QRect( 0, 0, maxItemWidth(), i->height(this)),
                               g, QStyle::Style_FocusAtBorder,
                               QStyleOption(i->isSelected() ? g.highlight() :
                                            g.base() ) );
    }
    p->restore();
}

KIFFileList& KIFFileList::operator=(const KIFFileList &src)
{
    clear();
    unsigned int i;
    for(i=0; i < src.count(); ++i)
        insertItem(src.text(i));
    if(src.currentItem() != -1)
        setCurrentItem(src.currentItem());
    return(*this);
}

void KIFFileList::dropEvent(QDropEvent *ev)
{
    QStringList fileList;
    if(!QUriDrag::decodeLocalFiles(ev, fileList)){
        qWarning("Pixie: Can't decode drop.");
        return;
    }
    if(!fileList.count())
        return;
    bool isImage;
    bool err = false;
    for(QStringList::Iterator it = fileList.begin(); it != fileList.end(); ++it){
        KURL url("file:" + (*it));
        isImage =  KMimeType::findByURL(url, true, true)->name().left(6) ==
            "image/";
        if(isImage)
            slotAppend(*it);
        else if(!err){
            KMessageBox::sorry(this, i18n("You may only drop images on the FileList!"));
            err = true;
        }
    }
}

void KIFFileList::dragEnterEvent(QDragEnterEvent *ev)
{
    ev->accept(QUriDrag::canDecode(ev));

}


