/***************************************************************************
 *   Copyright 2007-2008 Wouter Haffmans <cheetah@simply-life.net>         *
 *                                                                         *
 *   This program 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 2 of        *
 *   the License or (at your option) version 3 or any later version        *
 *   accepted by the membership of KDE e.V. (or its successor approved     *
 *   by the membership of KDE e.V.), which shall act as a proxy            *
 *   defined in Section 14 of version 3 of the license.                    *
 *                                                                         *
 *   This program 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 "drawingwriter.h"

#include <QByteArray>
#include <QDataStream>
#include <QBuffer>
#include <QDomDocument>

#include <KTemporaryFile>
#include <kio/job.h>
#include <kio/copyjob.h>
#include <KFilterDev>

#include "graphicslinesitem.h"
#include "palette.h"
#include "canvasscene.h"
#include "palettemanagerxml.h"

#include <QtDebug>

DrawingWriter::DrawingWriter()
{
    setBackgroundStyle(CanvasScene::center);
}

DrawingWriter::~DrawingWriter()
{
    // Nothing to do
}

bool DrawingWriter::save(KUrl url, int version)
{
    switch(version)
    {
    case 1:
    default:
        QByteArray data = this->saveVersion1();
        qDebug() << "Got data " << data.size();
        KTemporaryFile temp;
        if (!temp.open()) {
            qDebug() << "Error opening temp";
            return false;
        }
        QDataStream outStream(&temp);
        outStream.writeRawData(data.constData(), data.size());
        qDebug() << "Wrote " << temp.fileName();
        temp.setAutoRemove(false);

        // Copy file to URL
        KIO::copy(KUrl(temp.fileName()), url, KIO::Overwrite);
        qDebug() << "Copy triggered";
        return true;
    }
}

void DrawingWriter::setBackgroundImage(QImage background)
{
    m_background = background;
}

void DrawingWriter::setBackgroundStyle(CanvasScene::BackgroundStyle backgroundStyle)
{
    m_backgroundStyle = backgroundStyle;
}

void DrawingWriter::setPalette(Palette palette, QString name)
{
    m_palette = palette;
    if (!name.isNull()) {
        m_paletteName = name;
    }
}

void DrawingWriter::setLines(QList<GraphicsLinesItem *> lines)
{
    m_lines = lines;
}

QByteArray DrawingWriter::saveVersion1()
{
    QDomDocument outFile;
    QDomElement rootElement = outFile.createElement("kidDraw");
    outFile.appendChild(rootElement);
    // V1 is really KidDraw 2.0 :)
    rootElement.setAttribute("version", "2.0");

    writePaletteV1(rootElement);
    writeBackgroundV1(rootElement);
    writeLinesV1(rootElement);

    QByteArray data = outFile.toByteArray(2);
    QByteArray outData;
    QBuffer outBuffer(&outData);
    QIODevice *filter = KFilterDev::device(&outBuffer, "application/x-gzip", false);
    filter->open(QIODevice::WriteOnly);
    long int written = 0;
    while (written != data.size()) {
        written += filter->write(data);
        qDebug() << "Wrote " << written << " bytes total";
    }

    delete filter;
    return outData;
}

void DrawingWriter::writePaletteV1(QDomElement rootElement)
{
    QDomDocument document = rootElement.ownerDocument();
    QDomElement palette = document.createElement("palette");
    if (!m_paletteName.isEmpty()) {
        palette.setAttribute("name", m_paletteName);
    }

    Q_FOREACH(const Color &c, m_palette) {
        // Use palettemanager's XML functions
        palette.appendChild(PaletteManagerXML::createColorDomElement(document, c));
    }

    rootElement.appendChild(palette);
}

void DrawingWriter::writeBackgroundV1(QDomElement rootElement)
{
    // No background
    if (m_background.isNull()) {
        return;
    }

    QDomDocument document = rootElement.ownerDocument();
    QDomElement background = document.createElement("background");
    background.setAttribute("style", CanvasScene::backgroundStyleToString(m_backgroundStyle));

    // Create Base64 of PNG image as CData content
    QByteArray data;
    QBuffer buffer(&data);
    buffer.open(QIODevice::WriteOnly);
    m_background.save(&buffer, "PNG");

    QDomCDATASection dataSection =
            document.createCDATASection(QString(data.toBase64()));
    background.appendChild(dataSection);

    rootElement.appendChild(background);
}

void DrawingWriter::writeLinesV1(QDomElement rootElement)
{
    QDomDocument document = rootElement.ownerDocument();
    QDomElement lines = document.createElement("lines");

    QDomElement lineElement;

    Q_FOREACH(GraphicsLinesItem *line, m_lines) {
        lineElement = document.createElement("line");
        lineElement.setAttribute("penColor", line->tag());
        lineElement.setAttribute("penWidth", line->pen().width());
        lineElement.setAttribute("zValue", line->zValue());

        QStringList pointsStrings;
        Q_FOREACH(const QPointF &point, line->points()) {
            pointsStrings += QString::number(point.x()) + ',' + QString::number(point.y());
        }
        lineElement.setAttribute("points", pointsStrings.join(" "));
        lines.appendChild(lineElement);
    }

    rootElement.appendChild(lines);
}
