//
// Created by AmirS on 26.04.2025.
//

#include "UiElement.h"
#include <QXmlStreamReader>
#include <QRegularExpression>
#include <utility>

UiElement::UiElement(const int x1, const int y1, const int x2, const int y2, QString text, QString className,
                     const bool clickable)
    : m_x1(x1), m_y1(y1), m_x2(x2), m_y2(y2), m_text(std::move(text)), m_className(std::move(className)),
      m_clickable(clickable) {
}

static const QRegularExpression boundsRegex(R"(\[([0-9]+),([0-9]+)\]\[([0-9]+),([0-9]+)\])");

UiElement UiElement::fromXmlNode(const QXmlStreamReader &xmlReader) {
    int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
    QString text, className;
    bool clickable = false;

    if (xmlReader.attributes().hasAttribute("bounds")) {
        QString bounds = xmlReader.attributes().value("bounds").toString();
        QRegularExpressionMatch match = boundsRegex.match(bounds);
        if (match.hasMatch()) {
            x1 = match.captured(1).toInt();
            y1 = match.captured(2).toInt();
            x2 = match.captured(3).toInt();
            y2 = match.captured(4).toInt();
        }
    }

    if (xmlReader.attributes().hasAttribute("text")) {
        text = xmlReader.attributes().value("text").toString();
    }

    if (xmlReader.attributes().hasAttribute("class")) {
        className = xmlReader.attributes().value("class").toString();
    }

    if (xmlReader.attributes().hasAttribute("clickable")) {
        clickable = xmlReader.attributes().value("clickable").toString() == "true";
    }

    return UiElement(x1, y1, x2, y2, text, className, clickable);
}
