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

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 <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 "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" )
  , is_lmb_down(false)
  , pDlg( 0 )
{
    initialize( url );
}

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

void URLButton::initialize( const QString& url )
{
    urlStr = url;
    KURL u(url);
    local = u.isLocalFile();
    setIconURL(u);
    connect( this, SIGNAL(clicked()), SLOT(slotExec()) );
    setAcceptDrops( !Kicker::kicker()->isImmutable() );
    setToolTip();
}

void URLButton::saveConfig( KConfigGroup& config ) const
{
    config.writeEntry("URL", urlStr);
}

void URLButton::setToolTip()
{
    if (local)
    {
        KDesktopFile df(KURL(urlStr).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, urlStr);
        setTitle(urlStr);
    }
}

void URLButton::dragEnterEvent(QDragEnterEvent *ev)
{
    if (QUriDrag::canDecode(ev))
	ev->accept(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(urlStr);
        if(!execList.isEmpty())  {
             if (KDesktopFile::isDesktopFile(url.path())){
                KApplication::startServiceByDesktopPath(url.path(), execList,
                                                        0, 0, 0, "", true);
             }
             else // attempt to interpret path as directory
             {
                 KFileItem item( url, QString::fromLatin1( "inode/directory" ), -1 );
                 KonqOperations::doDrop( &item, 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(urlStr.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(KMimeType::iconForURL(KURL(urlStr)),
                                                 KIcon::Panel, sz,
                                                 KIcon::DefaultState, 0L, true);
    dd->setPixmap(pm);
    dd->dragCopy();
}

void URLButton::slotExec()
{
    KIconEffect::visualActivate(this, rect());
    kapp->propagateSessionManager();
    new KRun(urlStr, 0, local);
}

void URLButton::updateURL()
{
    if (pDlg->kurl().path() != urlStr) {
        urlStr = pDlg->kurl().path();
        setIconURL( pDlg->kurl() );
    }

    pDlg = 0L;
    setIconURL(urlStr);
    setToolTip();
    emit requestSave();
}

void URLButton::properties()
{
    if ( (local && !QFile::exists(KURL(urlStr).path()) )
         || KURL(urlStr).isMalformed())
    {
        KMessageBox::error( 0L, i18n("The file %1 doesn't exist").arg(urlStr) );
        return;
    }

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