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

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"

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

ServiceButton::ServiceButton( const KService::Ptr &service, QWidget* parent )
  : PanelButton( parent, "ServiceButton" )
  , _service(service)
  , _id(service->storageId())
  , is_lmb_down(false)
{
    if (_id.startsWith("/"))
    {
       QString tmp = KGlobal::dirs()->relativeLocation("appdata", _id);
       if (!tmp.startsWith("/"))
          _id = ":"+tmp;
    }
    initialize();
}

ServiceButton::ServiceButton( const KConfigGroup& config, QWidget* parent )
  : PanelButton( parent, "ServiceButton" )
  , is_lmb_down(false)
{
    QString id;
    if (config.hasKey("StorageId"))
       id = config.readPathEntry("StorageId");
    else
       id = config.readPathEntry("DesktopFile");
    loadServiceFromId(id);
    initialize();
}

ServiceButton::~ServiceButton()
{
}

void ServiceButton::loadServiceFromId(const QString &id)
{
    _id = id;
    if (_id.startsWith(":"))
    {
       _id = locate("appdata", id.mid(1));
       if (!_id.isEmpty())
       {
          KDesktopFile df(_id, true);
          _service = new KService(&df);
       }
       else
       {
          _service = 0;
       }
    }
    else
    {
       _service = KService::serviceByStorageId(_id);
       if (_service)
          _id = _service->storageId();
    }
    if (_id.startsWith("/"))
    {
       QString tmp = KGlobal::dirs()->relativeLocation("appdata", _id);
       if (!tmp.startsWith("/"))
          _id = ":"+tmp;
    }
}

void ServiceButton::initialize()
{
    readDesktopFile();
    connect( this, SIGNAL(clicked()), SLOT(slotExec()) );
}

void ServiceButton::readDesktopFile()
{
    if ( !_service || !_service->isValid() )
    {
        _valid = false;
        return;
    }
    QToolTip::remove( this );
    if ( !_service->genericName().isEmpty() ) {
        QToolTip::add(  this, _service->genericName() );
    }
    else if ( _service->comment().isEmpty() ) {
        QToolTip::add( this, _service->name() );
    } else {
        QToolTip::add( this, _service->name() + " - " + _service->comment() );
    }
    setTitle( _service->name() );
    setIcon( _service->icon() );
}

void ServiceButton::saveConfig( KConfigGroup& config ) const
{
    config.writePathEntry("StorageId", _id );
    if (!config.hasKey("DesktopFile") && _service)
       config.writePathEntry("DesktopFile", _service->desktopEntryPath());
}

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

void ServiceButton::dropEvent( QDropEvent* ev )
{
    KURL::List uriList;
    if( KURLDrag::decode( ev, uriList ) && _service ) {
        kapp->propagateSessionManager();
        KRun::run( *_service, 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 || !_service || (e->state() & LeftButton) == 0) return;

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

    setDown(false);

    QString path = _service->desktopEntryPath();

    // If the path to the desktop file is relative, try to get the full
    // path from KStdDirs.
    path = locate("apps", path);

    KURL url;
    url.setPath(path);

    PanelDrag* dd = new PanelDrag( KURL::List(url), this );

    dd->setPixmap( _service->pixmap(KIcon::Small) );
    dd->drag();
}

void ServiceButton::slotExec()
{
    if (!_service) return;
    KIconEffect::visualActivate(this, rect());

    KURL::List uriList;
    kapp->propagateSessionManager();
    KRun::run( *_service, uriList );
}

void ServiceButton::properties()
{
    if (!_service) return;
    QString path = _service->desktopEntryPath();

    // If the path to the desktop file is relative, try to get the full
    // path from KStdDirs.
    path = locate("apps", path);
    KURL serviceURL;
    serviceURL.setPath( path );
    KPropertiesDialog* dialog = new KPropertiesDialog( serviceURL, 0L, 0L, false, false ); // will delete itself
    dialog->setFileNameReadOnly(true);
    connect( dialog, SIGNAL(saveAs(const KURL &, KURL &)), SLOT( slotSaveAs(const KURL &, KURL &)));
    connect( dialog, SIGNAL(propertiesClosed()), SLOT( slotUpdate()));
    dialog->show();
}

void ServiceButton::slotUpdate()
{
    loadServiceFromId(_id);
    readDesktopFile();    
}

void ServiceButton::slotSaveAs(const KURL &oldUrl, KURL &newUrl)
{
    QString oldPath = oldUrl.path();
    if (locateLocal("appdata", oldUrl.fileName()) != oldPath)
    {
       QString path = newDesktopFile(oldUrl);
       newUrl.setPath(path);
       _id = path;
    }   
}
