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

Copyright (c) 2006 Stephan Binner <binner@kde.org>
                   Stephan Kulow <coolo@kde.org>
                   Dirk Mueller <mueller@kde.org>

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 <cassert>
#include <cmath>

#include <qtooltip.h>
#include <qpainter.h>
#include <qcursor.h>
#include <private/qeffects_p.h>

#include <klocale.h>
#include <kapplication.h>
#include <kstandarddirs.h>
#include <kiconloader.h>
#include <kdebug.h>

#include "kickerSettings.h"

#include "config.h"
#include "global.h"

#include "menumanager.h"
#include "k_mnu_stub.h"
#include "k_new_mnu.h"

#include "knewbutton.h"
#include "knewbutton.moc"

KNewButton *KNewButton::m_self = 0;

KNewButton::KNewButton( QWidget* parent )
    : KButton( parent ),
      m_movie(locate( "appdata", "pics/kmenu_basic.mng" )),m_oldPos(0,0)
{
    Q_ASSERT( !m_self );
    m_self = this;
    m_hoverTimer = -1;
    m_openTimer = -1;
    m_active = false;
    m_mouseInside = false;
    m_movie.pause();
    m_drag = false;

    setIconAlignment(AlignTop);
    setAcceptDrops(true);
    setIcon("kmenu-suse");
    setDrawArrow(false);
    m_orig_pixmap.load( locate( "appdata", "pics/kmenu_basic.mng" ) );
    m_pixmap = m_orig_pixmap;
    m_active_pixmap.load( locate( "appdata", "pics/kmenu_active.png" ) );
    QApplication::desktop()->screen()->installEventFilter(this);
    setMouseTracking(true);
}

KNewButton::~KNewButton()
{
    if ( m_self == this )
        m_self = 0;
    setMouseTracking(false);
}

void KNewButton::slotStatus(int status)
{
    if(status == QMovie::EndOfLoop)
        slotStopAnimation();
}

QColor KNewButton::borderColor() const
{
    QImage img = m_active_pixmap.convertToImage();
    return img.pixel( img.width() - 1, 0 );
}

void KNewButton::show()
{
     KButton::show();
     m_movie.connectUpdate(this, SLOT(updateMovie()));
     m_movie.connectStatus(this, SLOT(slotStatus(int)));
}

void KNewButton::updateMovie()
{
    m_oldPos = QPoint( -1, -1 );
    drawEye();
}

bool KNewButton::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::MouseButtonRelease ||
        e->type() == QEvent::MouseButtonPress   ||
        e->type() == QEvent::MouseButtonDblClick )
    {
        QMouseEvent *me = static_cast<QMouseEvent *>(e);
        if (rect().contains(mapFromGlobal(me->globalPos())))
        {
            if (m_pressedDuringPopup && m_popup && m_openTimer != -1
                    && (me->button() & Qt::LeftButton) )
                return true;
        }
    }

    if (e->type() == QEvent::MouseMove)
    {
        QMouseEvent *me = static_cast<QMouseEvent *>(e);
        if ((me->state() & MouseButtonMask) == NoButton) 
            drawEye();
    }

    return KButton::eventFilter(o, e);
}

void KNewButton::drawEye()
{
#define eye_x 62
#define eye_y 13
    QPoint mouse = QCursor::pos();
    QPoint me = mapToGlobal(QPoint(eye_x, eye_y));
    double a = atan2(mouse.y() - me.y(), mouse.x() - me.x());
    int dx = int(2.1 * cos(a));
    int dy = int(2.1 * sin(a));

    QPoint newpos(eye_x+dx,eye_y+dy);
    if (newpos!=m_oldPos) {
        m_oldPos = newpos;
        if (active())
            m_pixmap = m_active_pixmap;
        else
            m_pixmap = m_orig_pixmap;

        if(!m_movie.isNull() && m_movie.running() && !m_movie.framePixmap().isNull())
            m_pixmap = m_movie.framePixmap();

        QPainter p(&m_pixmap);
        p.setPen(white);
        p.setBrush(white);
        //      p.setPen(QColor(110,185,55));
        p.drawRect(eye_x+dx, eye_y+dy, 2, 2);
        p.end();

        repaint(false);
    }
#undef eye_x
#undef eye_y
}

void KNewButton::enterEvent(QEvent* e)
{
     KButton::enterEvent(e);

     m_mouseInside = true;
     if (KickerSettings::openOnHover())
        m_hoverTimer = startTimer(200);

     m_movie.unpause();
     m_movie.restart();
}

void KNewButton::dragEnterEvent(QDragEnterEvent* /*e*/)
{
    if (m_hoverTimer != -1)
        killTimer(m_hoverTimer);

    m_hoverTimer = startTimer(500);
    m_mouseInside = true;
    m_drag = true;
}

void KNewButton::dragLeaveEvent(QDragLeaveEvent* /*e*/)
{
    m_mouseInside = false;
    m_drag = false;
}

void KNewButton::leaveEvent(QEvent* e)
{
    m_mouseInside = false;
    if (m_hoverTimer != -1)
        killTimer(m_hoverTimer);
    m_hoverTimer = -1;

    KButton::leaveEvent(e);

    slotStopAnimation();
}

void KNewButton::slotStopAnimation()
{
     m_movie.restart();
     m_movie.pause();
     updateMovie();
}

const QPixmap& KNewButton::labelIcon() const
{
    return m_pixmap;
}

void KNewButton::slotExecMenu()
{
    if (m_openTimer != -1)
        killTimer(m_openTimer);

    m_openTimer = startTimer(QApplication::doubleClickInterval() * 3);

    KButton::slotExecMenu();

    assert(dynamic_cast<KMenu*>(m_popup));

    m_popup->move(KickerLib::popupPosition(popupDirection(), m_popup, this));
    // I wish KMenu would properly done itself when it closes. But it doesn't.

    bool useEffect = true; // could be QApplication::isEffectEnabled()
    useEffect = false; // too many Qt bugs to be useful
    if (m_drag)
	useEffect = false;

    m_drag = false; // once is enough

    if (useEffect) {
        switch (popupDirection()) {
        case KPanelApplet::Left:
            qScrollEffect(m_popup, QEffects::LeftScroll);
            break;
        case KPanelApplet::Up:
            qScrollEffect(m_popup, QEffects::UpScroll);
            break;
        case KPanelApplet::Right:
            qScrollEffect(m_popup, QEffects::RightScroll);
            break;
        case KPanelApplet::Down:
            qScrollEffect(m_popup, QEffects::DownScroll);
            break;
        }
    }
    else
        static_cast<KMenu*>(m_popup)->show();
}

void KNewButton::timerEvent(QTimerEvent* e)
{
    if (e->timerId() == m_hoverTimer) {

        if (m_mouseInside && !isDown())
            showMenu();

        killTimer(m_hoverTimer);
        m_hoverTimer = -1;
    }
    if (e->timerId() == m_openTimer)
    {
        killTimer(m_openTimer);
        m_openTimer = -1;
    }
}
