#include "util/serializationUtils.h"

#include <QJsonObject>
#include <QHash>

QString penStyleToString(Qt::PenStyle style)
{
    switch (style) {
    case Qt::NoPen:          return "none";
    case Qt::SolidLine:      return "solid";
    case Qt::DashLine:       return "dash";
    case Qt::DotLine:        return "dot";
    case Qt::DashDotLine:    return "dashDot";
    case Qt::DashDotDotLine: return "dashDotDot";
    default:                 return "solid";
    }
}

Qt::PenStyle penStyleFromString(const QString &str)
{
    static const QHash<QString, Qt::PenStyle> map = {
        {"none",        Qt::NoPen},
        {"solid",       Qt::SolidLine},
        {"dash",        Qt::DashLine},
        {"dot",         Qt::DotLine},
        {"dashDot",     Qt::DashDotLine},
        {"dashDotDot",  Qt::DashDotDotLine}
    };
    return map.value(str, Qt::SolidLine);
}

QJsonObject serializePen(const QPen &pen)
{
    QJsonObject obj;
    obj["color"] = pen.color().name(QColor::HexArgb);
    obj["width"] = pen.widthF();
    obj["style"] = penStyleToString(pen.style());
    return obj;
}

QPen deserializePen(const QJsonObject &obj)
{
    QPen pen;
    pen.setColor(QColor(obj["color"].toString()));
    pen.setWidthF(obj["width"].toDouble());
    pen.setStyle(penStyleFromString(obj["style"].toString()));
    return pen;
}

QJsonObject serializeBrush(const QBrush &brush)
{
    QJsonObject obj;
    obj["color"] = brush.color().name(QColor::HexArgb);
    return obj;
}

QJsonObject serializeCommon(const QGraphicsItem *item, const QString &type)
{
    QJsonObject obj;
    obj["type"] = type;
    obj["pos"] = QJsonObject{{"x", item->pos().x()}, {"y", item->pos().y()}};
    obj["rotation"] = item->rotation();
    obj["zValue"] = item->zValue();
    return obj;
}

void applyCommon(QGraphicsItem *item, const QJsonObject &obj)
{
    QJsonObject pos = obj["pos"].toObject();
    item->setPos(pos["x"].toDouble(), pos["y"].toDouble());
    item->setRotation(obj["rotation"].toDouble());
    item->setZValue(obj["zValue"].toDouble());
}
