/*****************************************************************************
 *
 * Testmanager - Graphical Automation and Visualisation Tool
 *
 * Copyright (C) 2019  Florian Pose <fp@igh.de>
 *
 * This file is part of Testmanager.
 *
 * Testmanager 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.
 *
 * Testmanager 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 Testmanager. If not, see <http://www.gnu.org/licenses/>.
 *
 ****************************************************************************/

#include "TextPlugin.h"

#include "TextPluginDialog.h"

#include "DataSlot.h"
#include "DataModel.h"
#include "DataNode.h"
#include "SlotModel.h"

#include <QtPdWidgets2/Text.h>

#include <QDebug>
#include <QJsonObject>

/****************************************************************************/

QString TextPlugin::name() const
{
    return tr("Text Display");
}

/****************************************************************************/

QIcon TextPlugin::icon() const
{
    return QIcon(":/images/plugin-text.svg");
}

/****************************************************************************/

void *TextPlugin::createPrivateData(QWidget *widget) const
{
    Pd::Text *text = dynamic_cast<Pd::Text *>(widget);
    if (!text) {
        qWarning() << __func__ << "failed to cast";
        return NULL;
    }

    Pd::Text::Hash *hash = new Pd::Text::Hash();
    text->setHash(hash);
    return hash;
}

/****************************************************************************/

void TextPlugin::readPrivateData(
        const QJsonObject &json,
        QWidget *widget,
        void *data) const
{
    Pd::Text *text = dynamic_cast<Pd::Text *>(widget);
    if (!text) {
        qWarning() << __func__ << "failed to cast";
        return;
    }

    Pd::Text::Hash *hash = static_cast<Pd::Text::Hash *>(data);

    hash->clear();

    QJsonObject hashObj(json["hash"].toObject());

    foreach (QString keyStr, hashObj.keys()) {
        int key = keyStr.toInt();
        QJsonObject val(hashObj[keyStr].toObject());
        hash->insert(key, val["text"].toString());
    }

    text->updateValueText();
}

/****************************************************************************/

QJsonObject TextPlugin::writePrivateData(QWidget *, const void *data) const
{
    const Pd::Text::Hash *hash = static_cast<const Pd::Text::Hash *>(data);

    QJsonObject hashObj;

    for (Pd::Text::Hash::const_iterator i = hash->begin(); i != hash->end();
         i++) {
        QJsonObject value;
        value["text"] = i->text;
        hashObj[QString::number(i.key())] = value;
    }

    QJsonObject ret;
    ret["hash"] = hashObj;
    return ret;
}

/****************************************************************************/

void TextPlugin::deletePrivateData(QWidget *widget, void *data) const
{
    Pd::Text *text = dynamic_cast<Pd::Text *>(widget);
    if (text) {
        text->setHash(NULL);
    }

    Pd::Text::Hash *hash = static_cast<Pd::Text::Hash *>(data);
    delete hash;
}

/****************************************************************************/

void TextPlugin::openEditor(QWidget *widget, void *data, QWidget *parent)
{
    Pd::Text *text = dynamic_cast<Pd::Text *>(widget);
    if (!text) {
        return;
    }

    Pd::Text::Hash *hash = static_cast<Pd::Text::Hash *>(data);

    TextPluginDialog dialog(hash, parent);
    if (dialog.exec() == QDialog::Accepted) {
        text->updateValueText();
    }
}

/****************************************************************************/

int TextPlugin::getSlotCapacity() const
{
    return 1;
}

/****************************************************************************/

int TextPlugin::getFreeSlots(const SlotModel &slotModel) const
{
    int used = slotModel.getChildCount();
    return !used ? 1 : 0;
}

/****************************************************************************/

void TextPlugin::appendVariable(
        QWidget *widget,
        void *,
        SlotModel *slotModel,
        DataNode *dataNode) const
{
    auto text(dynamic_cast<Pd::Text *>(widget));

    DataSlot *slot = new DataSlot(slotModel);
    slot->url = dataNode->nodeUrl();

    if (dataNode->getPeriod().count() > 0.0) {
        slot->period = std::chrono::milliseconds(200);
    }

    auto pv(dataNode->getVariable());
    if (!pv.empty()) {
        text->setVariable(
                pv,
                {},
                slot->period,
                slot->scale,
                slot->offset,
                slot->tau);
        dataNode->notifySubscribed(slot->period);
    }
}

/****************************************************************************/

void TextPlugin::connectDataSlots(
        QWidget *widget,
        void *,
        const SlotModel *slotModel,
        const DataModel *dataModel) const
{
    auto text(dynamic_cast<Pd::Text *>(widget));

    if (!slotModel->getChildCount()) {
        return;
    }

    DataSlot *slot(dynamic_cast<DataSlot *>(slotModel->getChildNode(0)));
    if (!slot) {
        return;
    }

    DataNode *dataNode(dataModel->findDataNode(slot->url));
    if (dataNode) {
        auto pv(dataNode->getVariable());
        if (!pv.empty()) {
            text->setVariable(
                    pv,
                    {},
                    slot->period,
                    slot->scale,
                    slot->offset,
                    slot->tau);
            dataNode->notifySubscribed(slot->period);
        }
    }
    else {
        qWarning() << tr("Url not found: %1").arg(slot->url.toString());
    }
}

/****************************************************************************/

void TextPlugin::clearVariables(QWidget *widget, void *) const
{
    auto text(dynamic_cast<Pd::Text *>(widget));
    text->clearVariable();
}

/****************************************************************************/

QWidget *TextPlugin::createWidget(QWidget *parent) const
{
    return new Pd::Text(parent);
}

/****************************************************************************/
