// SPDX-FileCopyrightText: 2024 g10 Code GmbH
// SPDX-FileContributor: Carl Schwan <carl@carlschwan.eu>
// SPDX-License-Identifier: GPL-2.0-or-later

#include "templateconfigurationpage.h"
#include "config.h"
#include "ui_templateconfigurationpage.h"

using namespace GpgPass::Config;

TemplateConfigurationPage::TemplateConfigurationPage(QWidget *parent)
    : GpgPassConfigModule(parent)
    , ui(new Ui::TemplateConfigurationPage)
{
    ui->setupUi(this);

    connect(ui->checkBoxUseTemplate, &QAbstractButton::toggled, this, &TemplateConfigurationPage::toggleTemplateSubentries);

    // Changed
    connect(ui->checkBoxUseTemplate, &QAbstractButton::toggled, this, &TemplateConfigurationPage::changed);
    connect(ui->checkBoxTemplateAllFields, &QAbstractButton::toggled, this, &TemplateConfigurationPage::changed);
    connect(ui->plainTextEditTemplate, &QPlainTextEdit::textChanged, this, &TemplateConfigurationPage::changed);
}

void TemplateConfigurationPage::save()
{
    auto config = ::Config::self();
    config->setTemplateEnabled(ui->checkBoxUseTemplate->isChecked());
    config->setPassTemplate(ui->plainTextEditTemplate->toPlainText().split(u'\n', Qt::SkipEmptyParts));
    config->setTemplateAllFields(ui->checkBoxTemplateAllFields->isChecked());
    config->save();
}

void TemplateConfigurationPage::load()
{
    const auto config = ::Config::self();
    ui->plainTextEditTemplate->setPlainText(config->passTemplate().join(u'\n'));
    ui->checkBoxTemplateAllFields->setChecked(config->templateAllFields());
    useTemplate(config->templateEnabled());
}

void TemplateConfigurationPage::defaults()
{
    const auto config = ::Config::self();
    ui->plainTextEditTemplate->setPlainText(config->defaultPassTemplateValue().join(u'\n'));
    ui->checkBoxTemplateAllFields->setChecked(config->defaultTemplateAllFieldsValue());
    useTemplate(config->defaultTemplateEnabledValue());
}

void TemplateConfigurationPage::toggleTemplateSubentries(bool enable)
{
    ui->plainTextEditTemplate->setEnabled(enable);
    ui->checkBoxTemplateAllFields->setEnabled(enable);
}

void TemplateConfigurationPage::useTemplate(bool useTemplate)
{
    ui->checkBoxUseTemplate->setChecked(useTemplate);
    toggleTemplateSubentries(useTemplate);
}
