/*****************************************************************************
 *
 * Testmanager - Graphical Automation and Visualisation Tool
 *
 * Copyright (C) 2018  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 "DialPlugin.h"

#include "DialPluginDialog.h"

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

#include <QtPdWidgets2/Dial.h>

#include <QDebug>
#include <QJsonObject>
#include <QJsonArray>

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

QString DialPlugin::name() const
{
    return tr("Dial / Analog Gauge");
}

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

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

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

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

    QGradientStops *stops = new QGradientStops();
    dial->setGradientStops(*stops);
    return stops;
}

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

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

    auto stops = static_cast<QGradientStops *>(data);

    stops->clear();

    auto array(json["gradientStops"].toArray());

    foreach (const QJsonValue &value, array) {
        QJsonObject obj(value.toObject());
        stops->append(QGradientStop(obj["value"].toDouble(),
                    QColor(obj["color"].toString())));
    }

    dial->setGradientStops(*stops);
}

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

QJsonObject DialPlugin::writePrivateData(QWidget *, const void *data) const
{
    auto stops = static_cast<const QGradientStops *>(data);

    QJsonArray stopsArray;

    foreach (auto stop, *stops) {
        QJsonObject value;
        value["value"] = stop.first;
        value["color"] = stop.second.name(QColor::HexArgb);
        stopsArray.append(value);
    }

    QJsonObject ret;
    ret["gradientStops"] = stopsArray;
    return ret;
}

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

void DialPlugin::deletePrivateData(QWidget *widget, void *data) const
{
    Pd::Dial *dial = dynamic_cast<Pd::Dial *>(widget);
    if (dial) {
        dial->setGradientStops(QGradientStops());
    }

    auto stops = static_cast<QGradientStops *>(data);
    delete stops;
}

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

void DialPlugin::openEditor(QWidget *widget, void *data, QWidget *parent)
{
    Pd::Dial *dial = dynamic_cast<Pd::Dial *>(widget);
    if (!dial) {
        return;
    }

    auto stops = static_cast<QGradientStops *>(data);

    DialPluginDialog dialog(stops, parent);
    if (dialog.exec() == QDialog::Accepted) {
        dial->setGradientStops(*stops);
    }
}

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

int DialPlugin::getSlotCapacity() const
{
    return 2;
}

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

int DialPlugin::getFreeSlots(const SlotModel &slotModel) const
{
    int ret = 2;
    for (int i = 0; i < slotModel.getChildCount(); ++i)
        ret -= slotModel.getChildNode(i)->getChildCount();
    if (ret < 0) {
        ret = 0;
    }
    return ret;
}

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

void DialPlugin::appendVariable(QWidget *widget, void *, SlotModel *slotModel,
        DataNode *dataNode) const
{
    auto dial(dynamic_cast<Pd::Dial *>(widget));

    if (slotModel->getChildCount() == 0) {
        // creating both SlotNodes
        new SlotNode(slotModel, tr("Display"));
        new SlotNode(slotModel, tr("Setpoint"));
    } else if (slotModel->getChildCount() != 2) {
        qFatal("Invalid number of SlotNodes");
    }

    SlotNode *node = slotModel->getChildNode(0);
    if (node->getChildCount() == 0) {
        DataSlot *slot = new DataSlot(node);
        slot->url = dataNode->nodeUrl();
        slot->period = std::chrono::milliseconds(100);

        auto pv(dataNode->getVariable());
        if (!pv.empty()) {
            dial->currentValue.setVariable(pv, {}, slot->period,
                    slot->scale, slot->offset, slot->tau);
            dataNode->notifySubscribed(slot->period);
        }
    }
    else {
        // append as setpoint variable
        node = slotModel->getChildNode(1);
        if (node->getChildCount() != 0)
            return;
        DataSlot *slot = new DataSlot(node);
        slot->url = dataNode->nodeUrl();

        auto pv(dataNode->getVariable());
        if (!pv.empty()) {
            // if slot is a signal, use periodic subscription
            if (!pv.isWriteable())
                slot->period = std::chrono::milliseconds(100);
            dial->setpointValue.setVariable(pv, {}, slot->period,
                    slot->scale, slot->offset, slot->tau);
            dataNode->notifySubscribed(slot->period);
        }
    }
}

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

void DialPlugin::connectDataSlots(QWidget *widget, void *,
        const SlotModel *slotModel, const DataModel *dataModel) const
{
    auto dial(dynamic_cast<Pd::Dial *>(widget));

    if (slotModel->getChildCount() > 0) { // display
        SlotNode *node = slotModel->getChildNode(0);
        if (node->getChildCount() > 0) {
            DataSlot *slot =
                dynamic_cast<DataSlot *>(node->getChildNode(0));
            if (slot) {
                DataNode *dataNode(dataModel->findDataNode(slot->url));
                if (dataNode) {
                    auto pv(dataNode->getVariable());
                    if (!pv.empty()) {
                        dial->currentValue.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());
                }
            }
        }
    }

    if (slotModel->getChildCount() > 1) { // setpoint
        SlotNode *node = slotModel->getChildNode(1);
        if (node->getChildCount() > 0) {
            DataSlot *slot =
                dynamic_cast<DataSlot *>(node->getChildNode(0));
            if (slot) {
                DataNode *dataNode(dataModel->findDataNode(slot->url));
                if (dataNode) {
                    auto pv(dataNode->getVariable());
                    if (!pv.empty()) {
                        dial->setpointValue.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 DialPlugin::clearVariables(QWidget *widget, void *) const
{
    auto dial(dynamic_cast<Pd::Dial *>(widget));
    dial->currentValue.clearVariable();
    dial->setpointValue.clearVariable();
}

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

QWidget *DialPlugin::createWidget(QWidget *parent) const
{
    return new Pd::Dial(parent);
}

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