/*
 * Copyright 2010 Mihai Niculescu <q.quark@gmail.com>
 *
 * This file is part of EqualX Project (https://launchpad.net/equalx/)
 *
 * EqualX is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * EqualX is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <QGridLayout>
#include <QEvent>
#include <QTimer>

#include "SymbolsGroupMenu.h"

SymbolsGroupMenu::SymbolsGroupMenu(QWidget * parent, int cols)
    : QMenu(parent),
      mMaxCols(cols),
      mCurCol(0),
      mCurRow(0),
      mHide(true)
{
    m_grid = new QGridLayout;
    m_grid->setContentsMargins(0 ,0, 0, 0);
    m_grid->setSpacing(0);

    //setFrameShadow(QFrame::Sunken);
    //setFrameShape(QFrame::Box);

    setLayout(m_grid);
}

void SymbolsGroupMenu::appendWidget(QWidget *widget)
{
    m_grid->addWidget(widget, mCurRow, mCurCol);

    mCurCol++;
    if(mCurCol >= mMaxCols) { mCurCol=0; mCurRow++; }

}

bool SymbolsGroupMenu::isEmpty()
{
    if(m_grid->count() > 0 )
        return false;
    else
        return true;
}

void SymbolsGroupMenu::popup()
{
    mHide = false;

    QWidget *parentWidget = (QWidget*)parent();

    if(parentWidget){
        QPoint p = parentWidget->mapToGlobal( QPoint(0,0));

        setGeometry(p.x(), p.y() + parentWidget->height(), parentWidget->width(), sizeHint().height() );
    }

    show();
}

void SymbolsGroupMenu::enterEvent(QEvent *event)
{
   showMenu();

    QMenu::enterEvent(event);
}

void SymbolsGroupMenu::leaveEvent(QEvent *event)
{

    if( event->type() == QEvent::Leave ){
        QTimer::singleShot(200, this, SLOT(hideMenu()) );
    }

    QMenu::leaveEvent(event);


}

void SymbolsGroupMenu::showMenu()
{
    mHide = false;

    if(isHidden() )
        show();
}

void SymbolsGroupMenu::hideMenu()
{
    //keep it if mouse is over parent widget

    if( !((QWidget*)parent())->underMouse() || underMouse()){
        QTimer::singleShot(200, this, SLOT(hideMenu()) );
    }
}
