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

Copyright (c) 2000 Matthias Elter

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 <qvalidator.h>
#include <qlayout.h>

#include <kdebug.h>
#include <khelpmenu.h>
#include <klocale.h>
#include <kglobal.h>
#include <kpopupmenu.h>
#include <kiconloader.h>
#include <kconfig.h>

#include "containerarea.h"
#include "customSize_dlg.h"
#include "kicker.h"
#include "fittslawframe.h"
#include "addcontainer_mnu.h"
#include "removecontainer_mnu.h"

#include "childpanelextension.h"
#include "childpanelextension.moc"

//Position p;

extern "C"
{
    KPanelExtension* init(QWidget *parent, const QString& configFile)
    {
        KGlobal::locale()->insertCatalogue("childpanelextension");
        return new ChildPanelExtension(configFile, KPanelExtension::Stretch,
                                       0, parent, "childpanelextension");
    }
}

ChildPanelExtension::ChildPanelExtension(const QString& configFile, Type type,
					 int actions, QWidget *parent, const char *name)
    : KPanelExtension(configFile, type, actions, parent, name)
    , DCOPObject(QCString("ChildPanel_") + QString::number( (ulong) this ).latin1() )
    , _opMnu( 0 )
    , built( false )
{
    QVBoxLayout* layout = new QVBoxLayout( this );

    // container area box
    _frame = new FittsLawFrame( this );
    layout->addWidget( _frame, 1 );

    _frame->setFrameStyle(QFrame::StyledPanel  | QFrame::Raised);
    _frame->setLineWidth(2);
    _frame->installEventFilter( this );

    layout = new QVBoxLayout( _frame );
    layout->setMargin( _frame->frameWidth() );

    // container area
    _containerArea = new ContainerArea( config(), _frame, opMenu() );
    layout->addWidget( _containerArea, 1 );

    _containerArea->setFrameStyle( QFrame::NoFrame );
    _containerArea->viewport()->installEventFilter( this );
    _containerArea->initialize( 0, false );
    _containerArea->show();

    // Make sure the containerarea has the right orientation from the
    // beginning.
    positionChange(position());
}

ChildPanelExtension::~ChildPanelExtension()
{
}

QPopupMenu* ChildPanelExtension::opMenu()
{
    if( _opMnu != 0 )
        return _opMnu;

    _opMnu = new QPopupMenu(this);

    connect(_opMnu, SIGNAL(aboutToShow()), this, SLOT(slotBuildOpMenu()));

    return _opMnu;
}

void ChildPanelExtension::positionChange( Position p )
{
    switch ( p ) {
    case Left: _containerArea->setPosition( ::Left ); break;
    case Right: _containerArea->setPosition( ::Right ); break;
    case Bottom: _containerArea->setPosition( ::Bottom ); break;
    case Top: _containerArea->setPosition( ::Top ); break;
    }

    _containerArea->setOrientation(orientation());
}

QSize ChildPanelExtension::sizeHint(Position p, QSize maxSize) const
{
    QSize size;
    if( p == Left || p == Right ) {
        size = QSize( sizeInPixels(),
                      _containerArea->minimumUsedSpace( Vertical,
                                                        sizeInPixels(),
                                                        maxSize.height() ) );
    } else {
        size = QSize( _containerArea->minimumUsedSpace( Horizontal,
                                                        maxSize.width(),
                                                        sizeInPixels() ),
                      sizeInPixels() );
    }
    return size.boundedTo( maxSize );
}

bool ChildPanelExtension::eventFilter( QObject*, QEvent * e)
{
    switch ( e->type() ) {
    case QEvent::MouseButtonPress:
	{
	    QMouseEvent* me = (QMouseEvent*) e;
	    if ( me->button() == RightButton )
		opMenu()->exec(me->globalPos());
	}
	break;
    default:
	break;
    }
    return false;
}

void ChildPanelExtension::slotSetupSizeMnu()
{
    _sizeMnu->setItemChecked(KPanelExtension::SizeTiny, false);
    _sizeMnu->setItemChecked(KPanelExtension::SizeSmall, false);
    _sizeMnu->setItemChecked(KPanelExtension::SizeNormal, false);
    _sizeMnu->setItemChecked(KPanelExtension::SizeLarge, false);
    _sizeMnu->setItemChecked(KPanelExtension::SizeCustom, false);

    if (sizeSetting() > KPanelExtension::SizeLarge)
    {
        _sizeMnu->setItemChecked(KPanelExtension::SizeCustom, true);
    }
    else
    {
        _sizeMnu->setItemChecked(sizeSetting(), true);
    }
}

void ChildPanelExtension::slotSetSize(int size)
{
    // get custom size
    slotSetupSizeMnu();

    if (size == KPanelExtension::SizeCustom)
    {
        customSizeDialog* sizeDialog = new customSizeDialog(this);

        if (sizeSetting() == KPanelExtension::SizeCustom)
        {
            sizeDialog->setCurrentSize(customSize());
        }

        connect(sizeDialog, SIGNAL(newCustomSize(int)),
                this, SLOT(slotSetCustomSize(int)));
        sizeDialog->show();
    }
    else
    {
        setSize(static_cast<Size>(size), customSize());

        // save the size setting here if it isn't a custom setting
        config()->setGroup("General");
        config()->writeEntry("Size", size);
        config()->sync();
    }

}

void ChildPanelExtension::slotSetCustomSize(int customSize)
{
    setSize(KPanelExtension::SizeCustom, customSize);
    config()->setGroup("General");
    config()->writeEntry("Size", KPanelExtension::SizeCustom);
    config()->writeEntry("CustomSize", customSize);
    config()->sync();
}

void ChildPanelExtension::addKMenuButton()
{
    _containerArea->addKMenuButton();
}

void ChildPanelExtension::addDesktopButton()
{
    _containerArea->addDesktopButton();
}

void ChildPanelExtension::addWindowListButton()
{
    _containerArea->addWindowListButton();
}

void ChildPanelExtension::addURLButton(const QString &url)
{
    _containerArea->addURLButton(url);
}

void ChildPanelExtension::addBrowserButton(const QString &startDir)
{
    _containerArea->addBrowserButton(startDir);
}

void ChildPanelExtension::addServiceMenuButton(const QString &, const QString& relPath)
{
    _containerArea->addServiceMenuButton(relPath);
}

void ChildPanelExtension::addNonKDEAppButton(const QString &filePath, const QString &icon, const QString &cmdLine, bool inTerm)
{
    _containerArea->addNonKDEAppButton(filePath, icon, cmdLine, inTerm);
}

void ChildPanelExtension::addApplet(const QString &desktopFile)
{
    _containerArea->addApplet(desktopFile);
}

void ChildPanelExtension::addAppletContainer(const QString &desktopFile) // bad name, can this go away?####
{
    addAppletContainer( desktopFile );
}

void ChildPanelExtension::slotBuildOpMenu()
{
    if(_opMnu && !built) {
	// setup addmenu and removemenu
	AddContainerMenu* addMnu = new AddContainerMenu(_containerArea, true, this);
	RemoveContainerMenu* removeMnu = new RemoveContainerMenu( _containerArea, true, this );

	// setup size menu
	_sizeMnu = new QPopupMenu(this);
	_sizeMnu->setCheckable(true);
	_sizeMnu->insertItem(i18n("Tiny"), KPanelExtension::SizeTiny);
	_sizeMnu->insertItem(i18n("Small"), KPanelExtension::SizeSmall);
	_sizeMnu->insertItem(i18n("Normal"), KPanelExtension::SizeNormal);
	_sizeMnu->insertItem(i18n("Large"), KPanelExtension::SizeLarge);
	_sizeMnu->insertItem(i18n("Custom..."), KPanelExtension::SizeCustom);
	connect(_sizeMnu, SIGNAL(aboutToShow()), SLOT(slotSetupSizeMnu()));
	connect(_sizeMnu, SIGNAL(activated(int)), SLOT(slotSetSize(int)));

	if (!Kicker::kicker()->isImmutable())
	{
	    _opMnu->insertItem(i18n("&Add"), addMnu);
	    _opMnu->insertItem(i18n("&Remove"), removeMnu);
	    _opMnu->insertSeparator();
	    _opMnu->insertItem(i18n("Si&ze"), _sizeMnu);
	    _opMnu->insertItem(SmallIconSet("configure"), i18n("&Configure Panel"),
			       Kicker::kicker(), SLOT(slotLaunchConfig()));
	    _opMnu->insertSeparator();
	}

	KHelpMenu* help = new KHelpMenu( this, KGlobal::instance()->aboutData(), false);
	_opMnu->insertItem(SmallIconSet("help"), i18n("&Help"), help->menu());
	_opMnu->adjustSize();

	built = true;
    }
}
