/*
 * 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 <QDebug>
#include <QPixmapCache>
#include <QRegion>
#include <QPainter>
#include <QPaintEvent>

#include "qzionimage.h"
#include "qzionobject_p.h"

static int MAX_CACHE_SIZE = 4096;  // 4 mb

QZionTiledPixmap::QZionTiledPixmap(const QPixmap pixmap, QZionImageBorder border)
        : _is_null(false)
{
    this->border = border;
    QRect rect;
    for(int i = 0; i < 9; i++) {
        rect = tileRectAtSize( (qzTilePosition) i, pixmap.size());
        if (rect.width() == 0 && rect.height() == 0)
            tiles[i] = QPixmap();
        else
            tiles[i] = pixmap.copy(rect);
    }
}

QRect QZionTiledPixmap::tileRectAtSize(const qzTilePosition num, QSize size)
{
    // Positioning of each tile
    // TILE: POINT                     SIZE
    // NW: (0, 0)                      (left, top)
    // N:  (left, 0)                   (width - left - right, top)
    // NE: (width - right, 0)          (right, top)
    // W:  (0, top)                    (left, height - top - bottom)
    // C:  (left, top)                 (width - left - right, height - top - bottom )
    // E:  (width - right, top)        (right,  height - top - bottom)
    // SW: (0, height - bottom)        (left, bottom)
    // S:  (left, height - bottom)     (width - left - right, bottom)
    // SE: (widht - right, height - bottom) (right, bottom)


    int w = size.width();
    int h = size.height();
    int tw, th, tx, ty;

    tw = th = tx = ty = 0;

    switch(num) {
        case NORTH_WEST:
            tx = 0;
            ty = 0;
            tw = border.left;
            th = border.top;
            break;
        case NORTH:
            tx = border.left;
            ty = 0;
            tw = w - border.left - border.right;
            th = border.top;
            break;
        case NORTH_EAST:
            tx = w - border.right;
            ty = 0;
            tw = border.right;
            th = border.top;
            break;
        case WEST:
            tx = 0;
            ty = border.top;
            tw = border.left;
            th = h - border.top - border.bottom;
            break;
        case MIDDLE:
            tx = border.left;
            ty = border.top;
            tw = w - border.left - border.right;
            th = h - border.top - border.bottom;
            break;
        case EAST:
            tx = w - border.right;
            ty = border.top;
            tw = border.right;
            th = h - border.top - border.bottom;
            break;
        case SOUTH_WEST:
            tx = 0;
            ty = h - border.bottom;
            tw = border.left;
            th = border.bottom;
            break;
        case SOUTH:
            tx = border.left;
            ty = h - border.bottom;
            tw = w - border.left - border.right;
            th = border.bottom;
            break;
        case SOUTH_EAST:
            tx = w - border.right;
            ty = h - border.bottom;
            tw = border.right;
            th = border.bottom;
            break;

    }

    return QRect(tx, ty, tw, th);
}

class QZionImagePrivate
{
public:
    QSize size;
    QPixmap pixmap;
    QZionImageBorder border;
    QZionTiledPixmap tiledPixmap;
};


QZionImage::QZionImage(QZionAbstractCanvas *canvas)
    : QZionObject(canvas), _QZionImage_data(new QZionImagePrivate)
{
    QPixmapCache::setCacheLimit(MAX_CACHE_SIZE);
}

QZionImage::QZionImage(QZionAbstractCanvas *canvas, const QString &filepath)
    : QZionObject(canvas), _QZionImage_data(new QZionImagePrivate)
{
    QPixmapCache::setCacheLimit(MAX_CACHE_SIZE);
    load(filepath);

    QZD(QZionImage);
    setSize(d->pixmap.size());
}

QZionImage::QZionImage(QZionAbstractCanvas *canvas, const QPixmap &pixmap)
    : QZionObject(canvas), _QZionImage_data(new QZionImagePrivate)
{
    QPixmapCache::setCacheLimit(MAX_CACHE_SIZE);

    setPixmap(pixmap);
    setSize(pixmap.size());
}

QZionImage::QZionImage(QZionAbstractCanvas *canvas, const QImage &image)
    : QZionObject(canvas), _QZionImage_data(new QZionImagePrivate)
{
    QPixmapCache::setCacheLimit(MAX_CACHE_SIZE);

    QPixmap pixmap = QPixmap::fromImage(image);
    setPixmap(pixmap);
    setSize(pixmap.size());
}

QZionImage::~QZionImage()
{
    delete _QZionImage_data;
}

QPixmap QZionImage::pixmap() const
{
    QZD(QZionImage);
    return d->pixmap;
}

bool QZionImage::load(const QString &filename)
{
    if (_filepath == filename)
        return true;

    _filepath = filename;

    QPixmap result;

    if (QPixmapCache::find(filename, result)) {
        setPixmap(result);
        return true;
    }

    if (!result.load(filename)) {
        clear();
        return false;
    }

    QPixmapCache::insert(filename, result);
    setPixmap(result);

    return true;
}

bool QZionImage::reload()
{
    QZD(QZionImage);

    if (d->pixmap.isNull())
        return true;

    QPixmap result;
    if (!result.load(_filepath)) {
        clear();
        return false;
    }

    QPixmapCache::insert(_filepath, result);
    setPixmap(result);

    return true;
}

void QZionImage::setPixmap(const QPixmap &p)
{
    QZD(QZionImage);

    d->tiledPixmap = QZionTiledPixmap();
    d->pixmap = p;
    if (visible() && canvas())
        changed();
}

void QZionImage::clear()
{
    setPixmap(QPixmap());
}

QSize QZionImage::size() const
{
    QZD(QZionImage);
    return d->size;
}

void QZionImage::setSize(const QSize &size)
{
    QZD(QZionImage);
    d->size = size;

    QZionObject::setSize(size);
}

void QZionImage::setBorder(const int left, const int right,
                           const int top, const int bottom)
{
    QZD(QZionImage);
    if (border().left == left && border().right == right &&
        border().top == top && border().bottom == bottom) {
        return;
    }

    if (left | right | top | bottom) {
        d->border = QZionImageBorder(left, right, top, bottom);
        d->tiledPixmap = QZionTiledPixmap(d->pixmap, d->border);
    } else {
        d->border = QZionImageBorder();
        d->tiledPixmap = QZionTiledPixmap();
    }

    if (visible() && canvas())
        changed();

}

void QZionImage::setBorder(QZionImageBorder border)
{
    setBorder(border.left, border.right, border.top, border.bottom);
}

QZionImageBorder QZionImage::border()
{
    QZD(QZionImage);
    return d->border;
}

void QZionImage::paint(QPainter *p)
{
    QZD(QZionImage);

    if (d->pixmap.isNull())
        return;

    if (!d->tiledPixmap.isNull()) {
        QPixmap tile;
        QRect rect;
        for(int i = 0; i < 9; i++) {
            tile = d->tiledPixmap.tile((QZionTiledPixmap::qzTilePosition) i);
            if (tile.isNull())
                continue;

            p->save();
            rect = d->tiledPixmap.tileRectAtSize(
                                (QZionTiledPixmap::qzTilePosition) i, size());
            // QPainter needs to stay in the exactly position
            // to draw an scaled pixmap correctly. Otherwise
            // it will scale the offset position too, and this
            // behavior is not wanted
            QPoint newPoint =  pos() + rect.topLeft();
            p->translate(pos() + rect.topLeft());
            p->scale((double) rect.width() / tile.width(),
                     (double) rect.height() / tile.height());
            p->drawPixmap(QPoint(0, 0), tile);
            p->restore();
        }

        return;
    }

    if (d->size == d->pixmap.size()) {
        p->drawPixmap(pos(), d->pixmap);
        return;
    }

    p->translate(pos());
    p->scale((double)d->size.width() / d->pixmap.size().width(),
             (double)d->size.height() / d->pixmap.size().height());
    p->drawPixmap(QPoint(0, 0), d->pixmap);
    p->scale(1, 1);
    p->translate(-pos());
}

QRect QZionImage::rect() const
{
    return QRect(pos(), size());
}

QColor QZionImage::color() const
{
    return QColor(255, 255, 255);
}

void QZionImage::setColor(const QColor &color)
{
    setOpacity(color.alpha());
}

void QZionImage::changed()
{
    QZionObject::changed();
}
