/*
 * Copyright (C) 2008 Instituto Nokia de Tecnologia. All rights reserved.
 *
 * This file is part of QZion.
 *
 * QZion 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.
 *
 * QZion 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 QZion.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * This file incorporates work covered by the following copyright and
 * permission notice:
 *
 *  Copyright 2006 Maurizio Monge <maurizio.monge@gmail.com>
 *
 *  BSD License
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Attention: note that even being named "BSD License" by the
 * copyright holder, the license above is a variation of the license
 * known as BSD License.  This variation is compatible with GNU GPL.
 */

#include "qzionabstractcanvas.h"
#include "qzionobject_p.h"

#include <QDebug>
#include <QRegion>
#include <QPainter>
#include <QPaintEvent>

#include "qzionobject.h"
#include "qzionabstractcanvas_p.h"


QSet<QZionObject*> QZionAbstractCanvasPrivate::grabbedItems;

QZionAbstractCanvas::QZionAbstractCanvas()
{
    _QZionAbstractCanvas_data = new QZionAbstractCanvasPrivate(this);
}

QZionAbstractCanvas::~QZionAbstractCanvas()
{
    delete _QZionAbstractCanvas_data;
}

QZionObject *QZionAbstractCanvas::itemAt(const QPoint &pt) const
{
    QZD(QZionAbstractCanvas);

    for (int i = d->items.size() - 1; i >= 0; i--) {
        QZionObject *obj = d->items[i];
        if (obj->visible() && obj->contains(pt))
            return obj;
    }

    return NULL;
}

QList<QZionObject*> QZionAbstractCanvas::itemsAt(const QPoint &pt) const
{
    QZD(QZionAbstractCanvas);
    QList<QZionObject*> retv;

    for (int i = d->items.size() - 1; i >= 0; i--) {
        QZionObject *obj = d->items[i];
        if (obj->visible() && obj->contains(pt))
            retv.append(obj);
    }
    return retv;
}

void QZionAbstractCanvas::setZValue(QZionObject *obj, int zValue)
{
    QZD(QZionAbstractCanvas);
    if (zValue < 0)
        return;

    int obj_pos = d->items.indexOf(obj);
    if (obj_pos == zValue)
        return;

    d->items.removeAt(obj_pos);
    d->items.insert(zValue, obj);

    if (obj->visible())
        d->updateAfterRestack(obj, obj_pos, zValue);
}

void QZionAbstractCanvas::raise(QZionObject *obj)
{
    QZD(QZionAbstractCanvas);
    if (d->items.last() == obj)
        return;

    int obj_pos = d->items.indexOf(obj);
    d->items.removeAt(obj_pos);
    d->items.append(obj);
    if (obj->visible())
        d->updateAfterRestack(obj, obj_pos, d->items.size() - 1);
}

void QZionAbstractCanvas::lower(QZionObject *obj)
{
    QZD(QZionAbstractCanvas);
    if (d->items.first() == obj)
        return;

    int obj_pos = d->items.indexOf(obj);
    d->items.removeAt(obj_pos);
    d->items.prepend(obj);

    if (obj->visible())
        d->updateAfterRestack(obj, obj_pos, 0);
}

void QZionAbstractCanvas::stackAbove(QZionObject *obj, QZionObject* ref)
{
    QZD(QZionAbstractCanvas);
    int obj_pos = d->items.indexOf(obj);
    int ref_pos = d->items.indexOf(ref);

    if (obj_pos == -1 || ref_pos == -1) {
        qCritical("QZionAbstractCanvas::stackAbove: "
                  "arguments must be of the same canvas.\n");
        return;
    }

    if (obj_pos == ref_pos + 1)
        return;

    d->items.removeAt(obj_pos);
    if (obj_pos < ref_pos)
        d->items.insert(ref_pos, obj);
    else
        d->items.insert(ref_pos + 1, obj);

    if (obj->visible())
        d->updateAfterRestack(obj, obj_pos, ref_pos + 1);
}

void QZionAbstractCanvas::stackBelow(QZionObject *obj, QZionObject* ref)
{
    QZD(QZionAbstractCanvas);
    int obj_pos = d->items.indexOf(obj);
    int ref_pos = d->items.indexOf(ref);

    if (obj_pos == -1 || ref_pos == -1) {
        qCritical("QZionAbstractCanvas::stackBelow: "
                  "arguments must be of the same canvas.\n");
        return;
    }

    if (obj_pos == ref_pos - 1)
        return;

    d->items.removeAt(obj_pos);
    if (obj_pos < ref_pos)
        d->items.insert(ref_pos - 1, obj);
    else
        d->items.insert(ref_pos, obj);

    if (obj->visible())
        d->updateAfterRestack(obj, obj_pos, ref_pos);
}

void QZionAbstractCanvas::addObject(QZionObject *obj)
{
    QZionAbstractCanvas *prev_canvas = obj->canvas();

    if (prev_canvas == this)
        return;

    if (prev_canvas)
        prev_canvas->removeObject(obj);

    QZD(QZionAbstractCanvas);
    d->items.append(obj);

    QZDP_VAR(obj, QZionObject, dobj);
    dobj->canvas = this;

    if (obj->visible())
        obj->changed();
}

void QZionAbstractCanvas::removeObject(QZionObject *obj)
{
    if (obj->canvas() != this)
        return;

    if (obj->visible()) {
        QZionObjectPrivate *da = obj->_QZionObject_data;
        invalidate(da->lastRect, false);
    }

    QZD(QZionAbstractCanvas);
    d->items.removeAll(obj);

    QZDP_VAR(obj, QZionObject, dobj);
    if (d->grabbedItems.contains(obj))
        d->grabbedItems.clear();

    dobj->canvas = 0;
}

const QList<QZionObject*> *QZionAbstractCanvas::items() const
{
    QZD(QZionAbstractCanvas);
    return &(d->items);
}

QZionObject *QZionAbstractCanvas::itemAt(const int x, const int y) const
{
    return itemAt(QPoint(x,y));
}

QList<QZionObject*> QZionAbstractCanvas::itemsAt(const int x,
                                                 const int y) const
{
    return itemsAt(QPoint(x,y));
}

int QZionAbstractCanvas::canvasWidth() const
{
    return 0;
}

int QZionAbstractCanvas::canvasHeight() const
{
    return 0;
}

int QZionAbstractCanvas::zValue(QZionObject *obj) const
{
    QZD(QZionAbstractCanvas);
    return d->items.indexOf(obj);
}

QPoint QZionAbstractCanvas::mapToLocal(const QPoint &pt) const
{
    return pt;
}

void QZionAbstractCanvas::mouseEventHandler(QMouseEvent *e,
                                            memberMouseAction m_ma,
                                            mouseAction ma)
{
    QZD(QZionAbstractCanvas);
    QPoint relativePoint = mapToLocal(e->pos());
    QMouseEvent re = QMouseEvent(e->type(), relativePoint, e->pos(),
                                 e->button(), e->buttons(), e->modifiers());

    QList<QZionObject *>::iterator it = d->items.end();
    while (it != d->items.begin()) {
        --it;
        QZionObject *obj = *it;

        if (d->grabbedItems.isEmpty()) {
            if (!obj->mouseEvents() || !obj->visible()
                || !obj->contains(relativePoint))
                continue;
        } else if (!d->grabbedItems.contains(obj)) {
                continue;
        }

        // Default for events is to be accepted. Handlers should explicitly
        // call event->ignore() to ignore them.
        re.setAccepted(true);
        (obj->*m_ma)(&re);

        if (re.isAccepted()) {
            if (m_ma == &QZionObject::mousePressEvent &&
                e->buttons() == e->button())
                d->grabbedItems.insert(obj);
            else if (m_ma == &QZionObject::mouseReleaseEvent &&
                     e->buttons() == Qt::NoButton)
                d->grabbedItems.remove(obj);

            // Calls the shorthand function of group for this event.
            // This is an easy way to a subclass of QZionGroup to
            // track its children events.
            (this->*ma)(obj, &re);
            return;
        }
    }

    // If no child handled the event, we just ignore it.
    e->ignore();
}

void QZionAbstractCanvas::mouseMoveEvent(QMouseEvent *e)
{
    mouseEventHandler(e, &QZionObject::mouseMoveEvent,
                      &QZionAbstractCanvas::mouseObjectMoveEvent);
}

void QZionAbstractCanvas::mousePressEvent(QMouseEvent *e)
{
    mouseEventHandler(e, &QZionObject::mousePressEvent,
                      &QZionAbstractCanvas::mouseObjectPressEvent);
}

void QZionAbstractCanvas::mouseReleaseEvent(QMouseEvent *e)
{
    mouseEventHandler(e, &QZionObject::mouseReleaseEvent,
                      &QZionAbstractCanvas::mouseObjectReleaseEvent);
}


/* Maybe we can unify all event handlers in the future,
   as this method has some code in common with mouseEventHandler() */
void QZionAbstractCanvas::wheelEvent(QWheelEvent *e)
{
    QZD(QZionAbstractCanvas);
    QPoint relativePoint = mapToLocal(e->pos());
    QWheelEvent re = QWheelEvent(relativePoint, e->pos(), e->delta(),
                                 e->buttons(), e->modifiers(),
                                 e->orientation());

    QList<QZionObject *>::iterator it = d->items.end();
    while (it != d->items.begin()) {
        --it;
        QZionObject *obj = *it;

        // XXX: to Edje, wheel is a mouse event, so we check it here
        if (!obj->mouseEvents() || !obj->visible()
            || !obj->contains(relativePoint))
            continue;

        // Default for events is to be accepted.  Handlers should explicitly
        // call event->ignore() to ignore them.
        re.setAccepted(true);
        obj->wheelEvent(&re);

        if (re.isAccepted()) {
            // Calls the shorthand function of group for this event.
            // This is an easy way to a subclass of QZionGroup to
            // track its children events.
            wheelObjectEvent(obj, &re);
            return;
        }
    }

    // If no child handled the event, we just ignore it.
    e->ignore();
}
