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

Copyright (c) 1996-2003 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 <qlayout.h>

#include <kdebug.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kpanelapplet.h>
#include <kapplication.h>
#include <algorithm>

#include "global.h"
#include "panel.h"
// TODO: Martijn Klingens
// #include "buttonop_mnu.h"
#include "appletop_mnu.h"
#include "popupposition.h"

#include "panelbutton.h"
#include "bookmarksbutton.h"
#include "browserbutton.h"
#include "desktopbutton.h"
#include "extensionbutton.h"
#include "kbutton.h"
#include "nonkdeappbutton.h"
#include "servicebutton.h"
#include "servicemenubutton.h"
#include "urlbutton.h"
#include "windowlistbutton.h"

#include "container_button.h"
#include "container_button.moc"

ButtonContainer::ButtonContainer(QPopupMenu* opMenu, QWidget* parent)
  : BaseContainer(opMenu, parent)
  , _button(0)
  , _layout(0)
  , _oldpos(0,0)
{
     setBackgroundOrigin( AncestorOrigin );
}

bool ButtonContainer::isValid() const
{
   if (_button)
      return _button->isValid();
   return true; // Can this happen?
}


// Buttons Shouldn't be square when larger than a certain size.
int ButtonContainer::widthForHeight(int height) const
{   if (isValid()) {
        int val=_button->preferredDimension(height);
        //kdDebug() << "ButtonContainer::widthForHeight("<<height<<"):" << val << endl<<flush;
        return val;
    }
    //kdDebug() << "ButtonContainer::widthForHeight -  NO VALID BUTTON!"<< endl<<flush;
    return height;
}

int ButtonContainer::heightForWidth(int width)  const
{   if (isValid()) {
        int val=_button->preferredDimension(width);
        //kdDebug() << "ButtonContainer::heightForWidth("<<width<<"):" << val << endl<<flush;
        return val;
    }
    //kdDebug() << "ButtonContainer::heightForWidth() - NO VALID BUTTON!"<< endl<<flush;
    return width;
}


void ButtonContainer::configure()
{
    if(_button) _button->configure();
}

void ButtonContainer::doSaveConfiguration( KConfigGroup& config, bool layoutOnly) const
{
    if(_button && !layoutOnly) _button->saveConfig( config );
}

void ButtonContainer::slotSetPopupDirection(Direction d)
{
    BaseContainer::slotSetPopupDirection(d);

    if(_button)
        _button->slotSetPopupDirection(d);
}

void ButtonContainer::slotSetOrientation(Orientation o)
{
    BaseContainer::slotSetOrientation(o);

    if(_button)
        _button->slotSetOrientation(o);
}

void ButtonContainer::embedButton(PanelButton* b)
{
    if (!b) return;

    delete _layout;
    _layout = new QVBoxLayout(this);
    _button = b;

    _button->installEventFilter(this);
    _layout->add(_button);
    connect(_button, SIGNAL(requestSave()), SIGNAL(requestSave()));
}

QPopupMenu* ButtonContainer::createOpMenu() const
{
    // TODO: Martijn Klingens
    // _opMnu = new PanelButtonOpMenu(_actions, _button->title(),
    //                                _button->icon());

    return new PanelAppletOpMenu(_actions, appletOpMenu(), 0, _button->title(),
                                 _button->icon(), const_cast<ButtonContainer*>(this));
}

bool ButtonContainer::eventFilter(QObject *o, QEvent *e)
{
    if (o == _button && e->type() == QEvent::MouseButtonPress)
    {
        static bool sentinal = false;

        if (sentinal)
        {
            return false;
        }

        sentinal = true;
        QMouseEvent* me = static_cast<QMouseEvent*>(e);
        switch (me->button())
        {
        case MidButton:
        {
            _button->setDown(true);
            _moveOffset = me->pos();
            emit moveme(this);
            sentinal = false;
            return true;
        }

        case RightButton:
        {
            if (!kapp->authorizeKAction("kicker_rmb"))
                break;

            _button->setZoomEnabled(false);
            qApp->syncX();
            qApp->processEvents();

            QPopupMenu* menu = opMenu();
            connect( menu, SIGNAL( aboutToHide() ), this, SLOT( slotMenuClosed() ) );
            switch(menu->exec( popupPosition( popupDirection(), menu, this, me->pos() )))
            {
            case PanelAppletOpMenu::Move:
                _moveOffset = rect().center();
                emit moveme(this);
                break;
            case PanelAppletOpMenu::Remove:
                emit removeme(this);
                break;
            case PanelAppletOpMenu::Help:
                help();
                break;
            case PanelAppletOpMenu::About:
                about();
                break;
            case PanelAppletOpMenu::Preferences:
                if (_button)
                    _button->properties();
                break;
            default:
                break;
            }

            _button->setZoomEnabled(true);
            sentinal = false;
            return true;
        }

        default:
            break;
        }

        sentinal = false;
    }
    return false;
}

void ButtonContainer::completeMoveOperation()
{
    if(_button)
        _button->setDown(false);
}

void ButtonContainer::slotMenuClosed()
{
    if (_button)
        _button->setDown(false);
}

// KMenuButton containerpan
KMenuButtonContainer::KMenuButtonContainer(QPopupMenu *opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new KButton(this) );
    _actions = PanelAppletOpMenu::KMenuEditor;
}

int KMenuButtonContainer::widthForHeight( int height ) const
{
    if ( height < 32 )
        return height + 10;
    else
        return ButtonContainer::widthForHeight(height);
}

int KMenuButtonContainer::heightForWidth( int width ) const
{
    if ( width < 32 )
        return width + 10;
    else
        return ButtonContainer::heightForWidth(width);
}

// DesktopButton container
DesktopButtonContainer::DesktopButtonContainer(QPopupMenu *opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new DesktopButton(this) );
}

// ServiceButton container
ServiceButtonContainer::ServiceButtonContainer( const QString& desktopFile,
                                                QPopupMenu* opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new ServiceButton( desktopFile, this ) );
    _actions = KPanelApplet::Preferences;
}

ServiceButtonContainer::ServiceButtonContainer( const KService::Ptr &service,
                                                QPopupMenu* opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new ServiceButton( service, this ) );
    _actions = KPanelApplet::Preferences;
}

ServiceButtonContainer::ServiceButtonContainer( const KConfigGroup& config,
                                                QPopupMenu* opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new ServiceButton( config, this ) );
    _actions = KPanelApplet::Preferences;
}

// URLButton container
URLButtonContainer::URLButtonContainer( const QString& url, QPopupMenu* opMenu, QWidget* parent )
  : ButtonContainer(opMenu, parent)
{
    embedButton( new URLButton( url, this ) );
    _actions = KPanelApplet::Preferences;
}

URLButtonContainer::URLButtonContainer( const KConfigGroup& config, QPopupMenu* opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new URLButton( config, this ) );
    _actions = KPanelApplet::Preferences;
}

// BrowserButton container
BrowserButtonContainer::BrowserButtonContainer(const QString &startDir, QPopupMenu* opMenu, const QString& icon, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new BrowserButton(icon, startDir, this) );
    _actions = KPanelApplet::Preferences;
}

BrowserButtonContainer::BrowserButtonContainer( const KConfigGroup& config, QPopupMenu* opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new BrowserButton(config, this) );
    _actions = KPanelApplet::Preferences;
}

// ServiceMenuButton container
ServiceMenuButtonContainer::ServiceMenuButtonContainer(const QString& relPath, QPopupMenu* opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new ServiceMenuButton(relPath, this) );
}

ServiceMenuButtonContainer::ServiceMenuButtonContainer( const KConfigGroup& config, QPopupMenu* opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new ServiceMenuButton(config, this) );
}

// WindowListButton container
WindowListButtonContainer::WindowListButtonContainer(QPopupMenu *opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new WindowListButton(this) );
}

// BookmarkButton container
BookmarksButtonContainer::BookmarksButtonContainer(QPopupMenu *opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new BookmarksButton(this) );
}

NonKDEAppButtonContainer::NonKDEAppButtonContainer(
        const QString &filePath, const QString &icon,
	const QString &cmdLine, bool inTerm,
	QPopupMenu* opMenu, QWidget* parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new NonKDEAppButton(filePath, icon, cmdLine, inTerm, this) );
    _actions = KPanelApplet::Preferences;
}

NonKDEAppButtonContainer::NonKDEAppButtonContainer( const KConfigGroup& config, QPopupMenu* opMenu, QWidget *parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new NonKDEAppButton(config, this) );
    _actions = KPanelApplet::Preferences;
}

// ExtensionButton container
ExtensionButtonContainer::ExtensionButtonContainer(const QString& df, QPopupMenu* opMenu, QWidget *parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new ExtensionButton(df, this) );
}

ExtensionButtonContainer::ExtensionButtonContainer( const KConfigGroup& config, QPopupMenu* opMenu, QWidget *parent)
  : ButtonContainer(opMenu, parent)
{
    embedButton( new ExtensionButton(config, this) );
}
