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

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 <kdesktopfile.h>
#include <kpropertiesdialog.h>
#include <krun.h>
#include <klocale.h>
#include <kurl.h>
#include <kstandarddirs.h>
#include <kicontheme.h>
#include <kiconeffect.h>

#include "kicker.h"

#include "servicebutton.h"
#include "servicebutton.moc"

class PanelDrag : public QUriDrag
{
public:
   PanelDrag(const QStrList &uris, QWidget *dragSource)
     : QUriDrag(uris, dragSource)
      { PanelButton::setZoomEnabled(false); }

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

ServiceButton::ServiceButton( const QString& desktopFile, QWidget* parent )
  : PanelButton( parent, "ServiceButton" )
  , _desktopFile( desktopFile )
  , is_lmb_down(false)
{
    initialize();
}

ServiceButton::ServiceButton( const KConfigGroup& config, QWidget* parent )
  : PanelButton( parent, "ServiceButton" )
  , _desktopFile( config.readEntry("DesktopFile") )
  , is_lmb_down(false)
{
    initialize();
}

void ServiceButton::initialize()
{
    readDesktopFile();

    connect( this, SIGNAL(clicked()), SLOT(slotExec()) );
    setAcceptDrops( !Kicker::kicker()->isImmutable() );
}

void ServiceButton::readDesktopFile()
{
    if ( _desktopFile.readComment().isEmpty() ) {
        QToolTip::add( this, _desktopFile.readName() );
    } else {
        QToolTip::add( this, _desktopFile.readName() + " - " + _desktopFile.readComment() );
    }
    setTitle( _desktopFile.readName() );
    setIcon( _desktopFile.readIcon() );
}

void ServiceButton::saveConfig( KConfigGroup& config ) const
{
    config.writeEntry( "DesktopFile", _desktopFile.filename() );
}

void ServiceButton::dragEnterEvent(QDragEnterEvent *ev)
{
    if (QUriDrag::canDecode(ev))
        ev->accept(rect());
    PanelButton::dragEnterEvent(ev);
}

void ServiceButton::dropEvent( QDropEvent* ev )
{
    QStrList uriList;
    if( QUriDrag::decode( ev, uriList ) ) {
        kapp->propagateSessionManager();
        KRun::run(
            KService( &_desktopFile ),
            KURL::List( QStringList::fromStrList( uriList ) ) );
    }
    PanelButton::dropEvent(ev);
}

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

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

void ServiceButton::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);

    KService service( &_desktopFile );

    QString path = service.desktopEntryPath();

    // If the path to the desktop file is relative, try to get the full
    // path from KStdDirs.
    path = (path[0] == '/') ? path : locate("apps", path);

    QStrList uris;
    uris.append( QUriDrag::localFileToUri( path ) );

    QDragObject* dd = new PanelDrag( uris, this );

    dd->setPixmap( service.pixmap(KIcon::Small) );
    dd->dragCopy();
}

void ServiceButton::slotExec()
{
    KIconEffect::visualActivate(this, rect());
    kapp->propagateSessionManager();
    KRun::run( KService( &_desktopFile ), KURL::List() );
}

void ServiceButton::properties()
{
    KService service( &_desktopFile );

    QString path = service.desktopEntryPath();

    // If the path to the desktop file is relative, try to get the full
    // path from KStdDirs.
    path = (path[0] == '/') ? path : locate("apps", path);

    KPropertiesDialog* dialog = new KPropertiesDialog( KURL(path) ); // will delete itself
    connect( dialog, SIGNAL(propertiesClosed()), SLOT(reinitialize()) );
}

void ServiceButton::reinitialize()
{
    _desktopFile.reparseConfiguration();
    readDesktopFile();
}
