/******************************************************************************
 * SVG Plugin
 * Unittest to develope the integration of animated svg files to the qt
 * interface of the testmanager.
 *
 * Jonathan Grahl <jonathan.grahl@igh.de>
******************************************************************************/


// ============================================================================
#include <QDebug>
#include <QDomElement>
#include <QFile>
#include <QPainter>
#include <QResizeEvent>
#include <QString>
#include <QSvgRenderer>

#include "SvgTest.h"



// ============================================================================
SvgPlugin::SvgPlugin(QWidget *parent):
    QFrame(parent),
    rep(500),
    currentRep(0),
    testID(1),
    numTestcases(2),
    flip(0),
    duration(0)
{

    // ---------- Init timer iterations for tests
    QObject::connect(&timer, SIGNAL(timeout()),
            this, SLOT(updateTests()));


    // ---------- Load information file to dom
    QString path = "images/voltmeter.svg";
    QFile file(path);

    qDebug() << "Load file to docs...";
    staticDoc.setContent(&file);
    file.close();
    completeDoc.setContent(&file);
    file.close();
    varDoc.setContent(&file);
    file.close();

    // ------------------------------------------------------------------------
    parseElements(completeDoc);



    // ------------------------------------------------------------------------
    /* Output to file for debugging. */

    // QString staticPath = "images/test1_static.svg";
    // QString varPath = "images/test1_var.svg";
    // QFile staticFile(staticPath);
    // QFile varFile(varPath);
    //
    // if(!staticFile.open(QIODevice::WriteOnly)) {
    //     qDebug() <<  "Failed to open static file!" ;
    // }
    //
    // QTextStream staticStream(&staticFile);
    // staticStream << staticDoc.toString(3);
    // staticFile.close();
    //
    // if(!varFile.open(QIODevice::WriteOnly)) {
    //     qDebug() <<  "Failed to open static file!" ;
    // }
    //
    // QTextStream varStream(&varFile);
    // varStream << varDoc.toString(3);
    // varFile.close();


    // ------------------------------------------------------------------------
    qDebug() << "Start test procedure...\n";
    timer.start(200);
}



// ============================================================================
void SvgPlugin::parseElements(QDomDocument &d) {

    // -------------------------- Find the msr-group --------------------------
    QDomNodeList elementList = d.elementsByTagName("g");
    for(int i = 0; i < elementList.length(); i++) {
        groupElem = elementList.at(i).toElement();
        QString attribute = groupElem.attribute("inkscape:label");

        if(attribute.compare("msr") == 0) {
            varElements.append(groupElem);
            msrGroup = groupElem;

        } else {
            staticElements.append(groupElem);

        }
    }

    // ------------------------- Find the msr-element -------------------------
    // ---------- Write all child elements to list
    QDomNodeList childElementList = msrGroup.elementsByTagName("path");
    for(int i  = 0; i < childElementList.length(); i++) {
        childElem = childElementList.at(i).toElement();
        QString label = childElem.attribute("msr");

        if(label.compare("idrot") == 0) {
            varElem = childElem;
            continue;
        }
    }
}



// ============================================================================
void SvgPlugin::createDocs(QList<QDomNode> &list) {

    for (int k = 0; k < list.length(); k++) {
        QDomNode node = list.at(k);
        node.parentNode().removeChild(node);

    }
}



// ============================================================================
void SvgPlugin::updateTests() {
        switch (testID) {
            case 1:
                testRenderComplete();
                break;

            case 2:
                testRenderDifferentiated();
                break;
        }

        currentRep++;
        if (currentRep > rep && testID < numTestcases) {
            qDebug() << "Test 1 (complete render) took: " << duration << " ms.";
            qDebug() << "  and " << duration / rep << " ms in mean per repetition.";

            duration = 0;
            parseElements(staticDoc);
            createDocs(varElements);
            renderer.load(staticDoc.toByteArray());

            parseElements(varDoc);
            createDocs(staticElements);

            currentRep = 0;
            testID++;

        } else if (currentRep > rep && testID >= numTestcases) {
            qDebug() << "Test 2 (differentiated render) took: " << duration << " ms.";
            qDebug() << "  and " << duration / rep << " ms in mean per repetition.";
            exit(0);
        }
}



// ============================================================================
void SvgPlugin::testRenderDifferentiated()
{
    QDateTime tStart = QDateTime::currentDateTime();

    changeColor();
    varRenderer.load(varDoc.toByteArray());
    update();

    duration += tStart.msecsTo(QDateTime::currentDateTime());
}



// ============================================================================
void SvgPlugin::testRenderComplete()
{
    QDateTime tStart = QDateTime::currentDateTime();

    changeColor();
    renderer.load(completeDoc.toByteArray());
    update();

    duration += tStart.msecsTo(QDateTime::currentDateTime());
}



// ============================================================================
void SvgPlugin::changeColor(){

    if (flip == 0) {
        flip = 1;
        varElem.setAttribute("style",
                "opacity:1;fill:#060000;stroke:#808080;stroke-width:0.1;"
                "stroke-linecap:round;stroke-linejoin:round;"
                "stroke-miterlimit:4;stroke-dasharray:none;"
                "stroke-dashoffset:0;fill-opacity:1");

    } else {
        flip = 0;
        varElem.setAttribute("style",
                "opacity:1;fill:#ef0000ff;stroke:#808080;stroke-width:0.1;"
                "stroke-linecap:round;stroke-linejoin:round;"
                "stroke-miterlimit:4;stroke-dasharray:none;"
                "stroke-dashoffset:0;fill-opacity:1");

    }
}



// ============================================================================
void SvgPlugin::paintEvent(QPaintEvent *event)
{
    QDateTime tStart = QDateTime::currentDateTime();

    QFrame::paintEvent(event);
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);


    // -------- Create rectangle for image and set to cintent size
    QSize size = contentsRect().size();
    QRect renderRect(QPoint(), size);

    renderer.render(&p, renderRect);
    varRenderer.render(&p, renderRect);

    duration += tStart.msecsTo(QDateTime::currentDateTime());

}
