/*
 * This file is part of smolbote. It's copyrighted by the contributors recorded
 * in the version control history of the file, available from its original
 * location: https://neueland.iserlohn-fortress.net/gitea/aqua/smolbote
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#include "profilemanagerdialog.h"
#include "profileview.h"
#include "ui_profilemanagerdialog.h"
#include <webprofile.h>
#include <QDir>
#include <QPointer>
#include "newprofiledialog.h"

ProfileManagerDialog::ProfileManagerDialog(const ProfileManager *profiles, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ProfileManagerDialog)
{
    ui->setupUi(this);

    connect(ui->listWidget, &QListWidget::itemPressed, this, &ProfileManagerDialog::showProfile);
    showProfile(nullptr);

    connect(ui->new_pushButton, &QPushButton::clicked, this, [=]() {
        auto *profileDlg = new NewProfileDialog(this);
        if(profileDlg->exec() == QDialog::Accepted) {
            emit createProfile(profileDlg->getId());
        }
        delete profileDlg;
    });

    connect(ui->delete_pushButton, &QPushButton::clicked, this, [=]() {
        deleteProfile(ui->listWidget->currentItem());
    });

    for(const QString &profileId : profiles->idList()) {
        addProfile(profiles->profile(profileId));
    }
}

ProfileManagerDialog::~ProfileManagerDialog()
{
    delete ui;
}

void ProfileManagerDialog::addProfile(WebProfile *profile)
{
    Q_CHECK_PTR(profile);

    auto *item = new QListWidgetItem(ui->listWidget);
    item->setText(profile->name());

    auto pointer = QPointer<WebProfile>(profile);
    item->setData(Qt::UserRole, QVariant::fromValue(pointer));
}

void ProfileManagerDialog::showProfile(QListWidgetItem *item)
{
    // clear out groupbox layout
    QLayoutItem *i;
    while((i = ui->groupBox->layout()->takeAt(0)) != nullptr) {
        delete i->widget();
        delete i;
    }

    if(item == nullptr) {
        ui->groupBox->setVisible(false);
        return;
    }
    ui->groupBox->setVisible(true);

    auto profile = item->data(Qt::UserRole).value<QPointer<WebProfile>>();
    auto *v = new ProfileView(profile.data(), this);
    ui->groupBox->layout()->addWidget(v);
    v->adjustSize();
}

void ProfileManagerDialog::deleteProfile(QListWidgetItem *item)
{
    if(item == nullptr)
        return;

    // clear out groupbox layout
    QLayoutItem *i;
    while((i = ui->groupBox->layout()->takeAt(0)) != nullptr) {
        delete i->widget();
        delete i;
    }

    auto profile = item->data(Qt::UserRole).value<QPointer<WebProfile>>();
    Q_ASSERT(!profile.isNull());

    emit removeProfile(profile);

    delete item;
}