#include "settingswidgets.hpp"

#include <QCheckBox>
#include <QFontComboBox>
#include <QKeySequenceEdit>
#include <QLineEdit>
#include <QSpinBox>

void SettingsWidget::save()
{
  if (objectName() != QLatin1String("General")) m_settings->beginGroup(objectName());

  // Int
  for (const auto *spinbox : findChildren<QSpinBox *>(QString(), Qt::FindDirectChildrenOnly)) {
    m_settings->setValue(spinbox->objectName(), spinbox->value());
  }

  // Bool
  for (const auto *checkbox : findChildren<QCheckBox *>(QString(), Qt::FindDirectChildrenOnly)) {
    m_settings->setValue(checkbox->objectName(), checkbox->isChecked());
  }

  // String
  for (const auto *lineedit : findChildren<QLineEdit *>(QString(), Qt::FindDirectChildrenOnly)) {
    m_settings->setValue(lineedit->objectName(), lineedit->text());
  }

  // Font
  for (const auto *font : findChildren<QFontComboBox *>(QString(), Qt::FindDirectChildrenOnly)) {
    m_settings->setValue(font->objectName(), font->currentFont().family());
  }

  // Shortcut
  for (const auto *shortcut : findChildren<QKeySequenceEdit *>(QString(), Qt::FindDirectChildrenOnly)) {
    m_settings->setValue(shortcut->objectName(), shortcut->keySequence());
  }

  if (objectName() != QLatin1String("General")) m_settings->endGroup();
}

void SettingsWidget::reset()
{
  if (objectName() != QLatin1String("General")) m_settings->beginGroup(objectName());

  // Int
  for (auto *spinbox : findChildren<QSpinBox *>(QString(), Qt::FindDirectChildrenOnly)) {
    const auto value = spinbox->property("defaultValue");
    spinbox->setValue(value.toInt());
    m_settings->setValue(spinbox->objectName(), value);
  }

  // Bool
  for (auto *checkbox : findChildren<QCheckBox *>(QString(), Qt::FindDirectChildrenOnly)) {
    const auto value = checkbox->property("defaultValue");
    checkbox->setChecked(value.toBool());
    m_settings->setValue(checkbox->objectName(), value);
  }

  // String
  for (auto *lineedit : findChildren<QLineEdit *>(QString(), Qt::FindDirectChildrenOnly)) {
    const auto value = lineedit->property("defaultValue");
    lineedit->setText(value.toString());
    m_settings->setValue(lineedit->objectName(), value);
  }

  // Font
  for (auto *font : findChildren<QFontComboBox *>(QString(), Qt::FindDirectChildrenOnly)) {
    const auto value = font->property("defaultValue");
    font->setFont(QFont(value.toString()));
    m_settings->setValue(font->objectName(), value);
  }

  // Shortcut
  for (auto *shortcut : findChildren<QKeySequenceEdit *>(QString(), Qt::FindDirectChildrenOnly)) {
    const auto value = shortcut->property("defaultValue");
    shortcut->setKeySequence(value.toString());
    m_settings->setValue(shortcut->objectName(), value);
  }

  if (objectName() != QLatin1String("General")) m_settings->endGroup();
}