/*
 * 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 "qzionobject.h"
#include "qzionobject_p.h"

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

#include "qzionrectangle.h"
#include "qzionabstractcanvas.h"
#include "qzioncommon.h"


QZionObjectPrivate::QZionObjectPrivate()
    : pos(QPoint(0,0)), opacity(255), visible(false), attributes(0),
      mouseEvents(true), clipper(NULL), canvas(NULL)
{
}

QZionObject::QZionObject(QZionAbstractCanvas *canvas)
    : QObject(), _QZionObject_data(new QZionObjectPrivate), _changed(false)
{
    if (canvas)
        canvas->addObject(this);
}

QZionObject::~QZionObject()
{
    QZD(QZionObject);

    setClipper(NULL);
    if (d->canvas)
        d->canvas->removeObject(this);
    delete d;
}

void QZionObject::setPos(const QPoint &newpos)
{
    QZD(QZionObject);

    if (d->pos != newpos) {
        d->pos = newpos;
        if (d->visible && d->canvas)
            changed();
    }
}

int QZionObject::opacity() const
{
    return _QZionObject_data->opacity;
}

void QZionObject::setOpacity(const int value)
{
    QZD(QZionObject);

    if (value == d->opacity)
        return;

    d->opacity = (value < 0) ? 0 : (value > 255) ? 255 : value;
    if (d->canvas && d->visible)
        changed();
}

void QZionObject::setVisible(const bool value)
{
    QZD(QZionObject);

    if (d->visible == value)
        return;

    d->visible = value;
    if (d->canvas)
        changed();
}

bool QZionObject::mouseEvents() const
{
    return _QZionObject_data->mouseEvents;
}

void QZionObject::setMouseEvents(const bool value)
{
    _QZionObject_data->mouseEvents = value;
}

int QZionObject::zValue() const
{
    QZD(QZionObject);

    if (d->canvas)
        return d->canvas->items()->indexOf(const_cast<QZionObject *>(this));
    else
        return -1;
}

void QZionObject::setZValue(const int zValue)
{
    QZD(QZionObject);

    if (d->canvas)
        d->canvas->setZValue(this, zValue);
}

void QZionObject::raise()
{
    QZD(QZionObject);

    if (d->canvas)
        d->canvas->raise(this);
}

void QZionObject::lower()
{
    QZD(QZionObject);

    if (d->canvas)
        d->canvas->lower(this);
}

void QZionObject::changed()
{
    QZD(QZionObject);

    _changed = true;
    if (d->canvas)
        d->canvas->ensurePendingUpdate();
}

QZionRectangle *QZionObject::clipper() const
{
    return _QZionObject_data->clipper;
}

void QZionObject::setClipper(QZionRectangle *rect)
{
    QZD(QZionObject);
    // There's no need to change clipper.
    if (d->clipper == rect)
        return;

    // Had an old clipper? Remove it.
    if (d->clipper) {
        d->clipper->removeClippee(this);
        d->clipper->decClipperRef();
        d->clipper = NULL;
    }

    // Has a new one? Add it.
    if (rect) {
        d->clipper = rect;
        d->clipper->addClippee(this);
        d->clipper->incClipperRef();
    }

    // Reflect changes
    if (d->canvas)
        changed();
}

void QZionObject::updateChanges()
{
    QZD(QZionObject);

    if (!_changed)
        return;

    if (d->canvas) {
        d->canvas->invalidate(d->lastRect, false);
        if(d->visible)
            d->canvas->invalidate(rect());
    }

    _changed = false;
}

QPixmap *QZionObjectPrivate::transparencePixmapCache = NULL;

QPixmap* QZionObjectPrivate::transparenceCache(const QSize &s)
{
    if (!transparencePixmapCache)
        transparencePixmapCache = new QPixmap();

    if (s.width() > transparencePixmapCache->width()
        || s.height() > transparencePixmapCache->height()) {
        /* Strange that a pixmap with alpha should be created this way,
           I think a qt bug */
        *transparencePixmapCache =
            QPixmap::fromImage(QImage(s.expandedTo(transparencePixmapCache->size()),
                                      QImage::Format_ARGB32));
    }

    return transparencePixmapCache;
}

void QZionObject::paintInternal(QPainter* pp, const QRect& /*prect*/,
                                const QRegion& /* preg */,
                                const QPoint& delta,
                                double cumulativeOpacity)
{
    QZD(QZionObject);

    d->lastRect = QRect();

    if (d->clipper != NULL) {
        int effectiveOpacity = d->clipper->effectiveColor().alpha();
        cumulativeOpacity *= (effectiveOpacity / 255.0);
    }

    int opacity = int(cumulativeOpacity * d->opacity + 0.5);

    if (opacity <= 0) {
        return;
    }

    pp->save();

    d->lastRect = rect().translated(delta);

    if (d->clipper != NULL) {
        QRect effectiveClipper = d->clipper->effectiveRect();
        if (pp->clipRegion().boundingRect().isNull())
            pp->setClipRect(effectiveClipper);
        else
            pp->setClipRegion(pp->clipRegion() & effectiveClipper);

        d->lastRect &= effectiveClipper.translated(delta);
    }

    if (opacity >= 255) {
        paint(pp);
    } else if (!layered()) {
        pp->setOpacity(opacity / 255.0);
        paint(pp);
        pp->setOpacity(1.0);
    } else {
        QRect mr = rect();
        QPixmap* cache = d->transparenceCache(mr.size());
        QPainter p(cache);

        /* clear */
        p.setBrush(QColor(255, 255, 255, 0));
        p.setPen(Qt::NoPen);
        p.setCompositionMode(QPainter::CompositionMode_Source);
        p.drawRect(QRect(QPoint(), mr.size()));

        /* paint on the item */
        p.translate(-mr.topLeft());
        paint(&p);
        p.translate(mr.topLeft());

        /* make the opacity */
        p.setBrush(QColor(255, 255, 255, 255 - opacity));
        p.setPen(Qt::NoPen);
        p.setCompositionMode(QPainter::CompositionMode_DestinationOut);
        p.drawRect(QRect(QPoint(), mr.size()));

        pp->drawPixmap(mr.topLeft(), *cache, QRect(QPoint(), mr.size()));
    }

    pp->restore();
}

QZionAbstractCanvas *QZionObject::canvas() const
{
    QZD(QZionObject);
    return d->canvas;
}

void QZionObject::stackAbove(QZionObject *ref)
{
    QZD(QZionObject);

    if (d->canvas)
        d->canvas->stackAbove(this, ref);
}

void QZionObject::stackBelow(QZionObject *ref)
{
    QZD(QZionObject);

    if (d->canvas)
        d->canvas->stackBelow(this, ref);
}

bool QZionObject::testAttribute(const Attributes attribute) const
{
    QZD(QZionObject);

    return (bool)(d->attributes & (1 << attribute));
}

void QZionObject::setAttribute(const Attributes attribute, const bool on)
{
    QZD(QZionObject);

    if (on)
        d->attributes |= (1 << attribute);
    else
        d->attributes &= ~(1 << attribute);
}

void QZionObject::setSize(const QSize &size)
{
    if (testAttribute(EmitSizeChanges))
        emit sizeChanged(size);
}

bool QZionObject::visible() const
{
    return _QZionObject_data->visible;
}

QPoint QZionObject::pos() const
{
    return _QZionObject_data->pos;
}

QColor QZionObject::effectiveColor() const
{
    QColor result;

    result = color();
    result.setAlpha(opacity());

    QZionRectangle *clip = clipper();
    if (clip)
        result = composeColorClass(result, clip->effectiveColor());

    return result;
}

QRect QZionObject::effectiveRect() const
{
    QRect result = rect();

    QZionRectangle *clip = clipper();
    if (clip)
        result &= clip->effectiveRect();

    return result;
}

bool QZionObject::contains(const QPoint &point) const
{
    return effectiveRect().contains(point);
}
