/*****************************************************************

Copyright (c) 1996-2000 the kicker authors. See file AUTHORS.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <qtooltip.h>
#include <qdragobject.h>
#include <qfile.h>

#include <kdesktopfile.h>
#include <kfileitem.h>
#include <konq_operations.h>
#include <kicontheme.h>
#include <kglobal.h>
#include <kiconeffect.h>
#include <kpropertiesdialog.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <krun.h>
#include <klocale.h>

#include <kdebug.h>

#include "kicker.h"

#include "urlbutton.h"
#include "urlbutton.moc"

#ifndef KDE_USE_FINAL // We get this from servicebutton.cpp with --enable-final
class PanelDrag : public QUriDrag
{
public:
   PanelDrag(const QStrList &uris, QWidget *dragSource)
     : QUriDrag(uris, dragSource)
      { PanelButton::setZoomEnabled(false); }

   ~PanelDrag()
      { PanelButton::setZoomEnabled(true); }
};
#endif

URLButton::URLButton( const QString& url, QWidget* parent )
  : PanelButton( parent, "URLButton" )
  , fileItem( 0 )
  , is_lmb_down(false)
  , pDlg( 0 )
{
    initialize( url );
}

URLButton::URLButton( const KConfigGroup& config, QWidget* parent )
  : PanelButton( parent, "URLButton" )
  , fileItem( 0 )
  , is_lmb_down(false)
  , pDlg( 0 )
{
    initialize( config.readPathEntry("URL") );
}

URLButton::~URLButton()
{
    delete fileItem;
}

void URLButton::initialize( const QString& url )
{
    fileItem = new KFileItem( KFileItem::Unknown, KFileItem::Unknown,
                              KURL( url ) );
    setIcon( fileItem->iconName() );
    connect( this, SIGNAL(clicked()), SLOT(slotExec()) );
    setToolTip();
}

void URLButton::saveConfig( KConfigGroup& config ) const
{
    config.writeEntry("URL", fileItem->url().prettyURL());
}

void URLButton::setToolTip()
{
    if (fileItem->isLocalFile() 
     && KDesktopFile::isDesktopFile(fileItem->url().path()))
    {
        KDesktopFile df(fileItem->url().path());
        if ( df.readComment().isEmpty() )
            QToolTip::add(this, df.readName());
        else
            QToolTip::add(this, df.readName() + " - " + df.readComment());
        setTitle(df.readName());
    }
    else
    {
        QToolTip::add(this, fileItem->url().prettyURL());
        setTitle(fileItem->url().prettyURL());
    }
}

void URLButton::dragEnterEvent(QDragEnterEvent *ev)
{
    if ((ev->source() != this) && fileItem->acceptsDrops() && QUriDrag::canDecode(ev))
	ev->accept(rect());
    else
        ev->ignore(rect());
    PanelButton::dragEnterEvent(ev);
}

void URLButton::dropEvent(QDropEvent *ev)
{
    kapp->propagateSessionManager();
    QStrList fileList;
    QStringList execList;
    if(QUriDrag::decode(ev, fileList)){
        QStrListIterator it(fileList);
        for(;it.current(); ++it)
            execList.append(it.current());
        KURL url( fileItem->url() );
        if(!execList.isEmpty())  {
             if (KDesktopFile::isDesktopFile(url.path())){
                KApplication::startServiceByDesktopPath(url.path(), execList,
                                                        0, 0, 0, "", true);
             }
             else // attempt to interpret path as directory
             {
                 KonqOperations::doDrop( fileItem, url, ev, this );
             }
        }
    }
    PanelButton::dropEvent(ev);
}

void URLButton::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == LeftButton) {
	last_lmb_press = e->pos();
	is_lmb_down = true;
    }
    QButton::mousePressEvent(e);
}

void URLButton::mouseReleaseEvent(QMouseEvent *e)
{
    if (e->button() == LeftButton) {
	is_lmb_down = false;
    }
    QButton::mouseReleaseEvent(e);
}

void URLButton::mouseMoveEvent(QMouseEvent *e)
{
    if (!is_lmb_down || (e->state() & LeftButton) == 0) return;

    QPoint p(e->pos() - last_lmb_press);
    if (p.manhattanLength() <= 16) // KGlobalSettings::dndEventDelay() is not enough!
	return;

    setDown(false);
    QStrList uris;
    uris.append(fileItem->url().prettyURL().local8Bit());
    QDragObject *dd = new PanelDrag(uris, this);

    KIcon::StdSizes sz = // Er, enum names should not be plural
	width() < 32 ?
	KIcon::SizeSmall : (width() < 48 ? KIcon::SizeMedium : KIcon::SizeLarge);

    QPixmap pm = KGlobal::iconLoader()->loadIcon(fileItem->iconName(),
                                                 KIcon::Panel, sz,
                                                 KIcon::DefaultState, 0L, true);
    dd->setPixmap(pm);
    dd->drag();
}

void URLButton::slotExec()
{
    KIconEffect::visualActivate(this, rect());
    kapp->propagateSessionManager();
    fileItem->run();
}

void URLButton::updateURL()
{
    if (pDlg->kurl() != fileItem->url()) {
	fileItem->setURL(pDlg->kurl());
	setIcon(fileItem->iconName());
	setToolTip();
	emit requestSave();
    }

    pDlg = 0L;
}

void URLButton::properties()
{
    if ( (fileItem->isLocalFile() && !QFile::exists(fileItem->url().path()) )
         || !fileItem->url().isValid())
    {
        KMessageBox::error( 0L, i18n("The file %1 doesn't exist")
	                            .arg(fileItem->url().prettyURL()) );
        return;
    }

    pDlg = new KPropertiesDialog(fileItem); // will delete itself
    connect(pDlg, SIGNAL(applied()), SLOT(updateURL()));
}
