#include "stylesheethandler.h"

#include <QWidget>

#include <QRegularExpression>

#include <QDebug>

QString StyleSheetHandler::find(const QString &styleSheet,
                                const QString &property, int index,
                                int &start, int &length) {
  auto propertyPattern = QString("%1:.*?;").arg(property);
  auto propertyMatch = QRegularExpression(propertyPattern).match(styleSheet);
  auto capturePattern =
      QString(R"(([^\s\d\w]{0,1}\w+))"); // [^\s\d\w] - punctuation category
  auto captures = QRegularExpression(capturePattern)
                      .globalMatch(propertyMatch.captured(0),
                                   property.length() + 1 /* ':' */);
  if (index > 0) {
    int captureIndex = 0;
    while (++captureIndex <= index)
      captures.next();
  }
  auto value = captures.next();
  start = propertyMatch.capturedStart(0) + value.capturedStart(0);
  length = value.capturedLength(0);
  return value.captured(0);
}

QVariant StyleSheetHandler::value(const QWidget *widget,
                                  const QString &property, int index) {
  if (widget == nullptr)
    return QVariant();

  int ignore;
  QString styleSheet = widget->styleSheet();
  if (styleSheet.isEmpty())
    return QVariant();

  QString result = find(styleSheet, property, index, ignore, ignore);
  return QVariant::fromValue(result);
}

void StyleSheetHandler::setValue(QWidget *widget, const QString &property,
                                 int index, const QVariant &value) {
  if (widget == nullptr)
    return;

  int start, length;
  QString styleSheet = widget->styleSheet();
  if (styleSheet.isEmpty())
    return;

  find(styleSheet, property, index, start, length);
  styleSheet = styleSheet.replace(start, length, value.toString());
  widget->setStyleSheet(styleSheet);
}
