#include "dirtree.h"
#include "fileop.h"
#include <klocale.h>
#include <kmessagebox.h>
#include <qdragobject.h>
#include <qfileinfo.h>
#include <qpopupmenu.h>

PixieDirTree::PixieDirTree(QWidget *parent, const char *name)
    : KFileTreeView(parent, name)
{
    setAcceptDrops(true);
    connect(this, SIGNAL(clicked(QListViewItem *)), this,
            SLOT(slotCurrentChanged(QListViewItem *)));
    connect(this, SIGNAL(dropped(KFileTreeView *, QDropEvent *, QListViewItem *)), this,
            SLOT(slotDropped(KFileTreeView *, QDropEvent *, QListViewItem *)));

    addColumn(i18n("Folders"));
    setAllColumnsShowFocus(true);
    setResizeMode(LastColumn);
    KFileTreeBranch *branch = addBranch(KURL("file:/"), "/");
    branch->setChildRecurse();
    setDirOnlyMode(branch, true);
    branch->setOpen(true);
}

PixieDirTree::~PixieDirTree()
{
    ;
}

bool PixieDirTree::acceptDrag(QDropEvent *ev) const
{
    // always allow, even if you don't have perms, so that subfolders expand
    QListViewItem *item, *par;
    const_cast<PixieDirTree*>(this)->findDrop(ev->pos(), par, item);
    if(!item)
        return(false);
    QStringList fileList;
    if(!QUriDrag::decodeLocalFiles(ev, fileList)){
        qWarning("Pixie: Can't decode drop.");
        return(false);
    }
    return(!fileList.isEmpty());
}

void PixieDirTree::slotDropped(KFileTreeView *, QDropEvent *ev, QListViewItem *item)
{
    QString destStr = ((KFileTreeViewItem *)item)->path();
    QFileInfo fi(destStr);
    if(!fi.isWritable()){
        qWarning("Can't drop here!");
        KMessageBox::sorry(this,
                           i18n("You do not have write permission for:") +
                           "\n" + destStr,
                           i18n("Folder Permission Error"));
        ev->ignore();
        return;
    }
    QStringList fileList;
    if(!QUriDrag::decodeLocalFiles(ev, fileList)){
        qWarning("Pixie: Can't decode drop.");
        return;
    }
    if(!fileList.count())
        return;
    int op;
    QPopupMenu opPopup;
    opPopup.insertItem(i18n("&Copy Here"), 1);
    opPopup.insertItem(i18n("&Move Here"), 2);
    opPopup.insertItem(i18n("&Link Here"), 3);

    QPoint pos = contentsToViewport(ev->pos());
    op = opPopup.exec(mapToGlobal(pos));
    switch(op){
    case 1:
        ev->setAction(QDropEvent::Copy);
        break;
    case 2:
        ev->setAction(QDropEvent::Move);
        break;
    case 3:
        ev->setAction(QDropEvent::Link);
        break;
    default:
        return;
    }
    // TESTING!!
    KIFFileTransfer::transferFiles(fileList, destStr, ev->action());
}

void PixieDirTree::slotCurrentChanged(QListViewItem *i)
{
    if(i){
        if(!i->isOpen()){
            KURL url(currentURL());
            qWarning("New current URL: %s", url.url().latin1());
            QFileInfo fi(url.directory() + "/" + url.fileName());
            emit locationChanged(fi.absFilePath());
        }
    }
}







#include "dirtree.moc"
