/*
    SPDX-FileCopyrightText: 2001 Marc Mutz <mutz@kde.org>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "emailaddressrequester.h"
#include "emailaddressselectiondialog.h"
#include <KLineEditEventHandler>
#include <KLocalizedString>
#include <QIcon>
#include <QLineEdit>
#include <QPointer>

#include <QHBoxLayout>
#include <QPushButton>
#include <QTreeView>

using namespace Akonadi;

class Akonadi::EmailAddressRequesterPrivate
{
public:
    explicit EmailAddressRequesterPrivate(EmailAddressRequester *qq)
        : q(qq)
    {
    }

    void slotAddressBook();

    EmailAddressRequester *const q;
    QLineEdit *mLineEdit = nullptr;
};

void EmailAddressRequesterPrivate::slotAddressBook()
{
    QPointer<Akonadi::EmailAddressSelectionDialog> dlg = new Akonadi::EmailAddressSelectionDialog(q);
    dlg->view()->view()->setSelectionMode(QAbstractItemView::MultiSelection);
    if (!dlg->exec()) {
        delete dlg;
        return;
    }

    QStringList addressList;
    const auto selectedAddresses = dlg->selectedAddresses();
    addressList.reserve(selectedAddresses.size());
    for (const Akonadi::EmailAddressSelection &selection : selectedAddresses) {
        addressList << selection.quotedEmail();
    }

    QString text = mLineEdit->text().trimmed();

    if (!text.isEmpty()) {
        if (!text.endsWith(u',')) {
            text += QLatin1StringView(", ");
        } else {
            text += u' ';
        }
    }

    mLineEdit->setText(text + addressList.join(u','));
    delete dlg;
}

EmailAddressRequester::EmailAddressRequester(QWidget *parent)
    : QWidget(parent)
    , d(new EmailAddressRequesterPrivate(this))
{
    auto layout = new QHBoxLayout(this);
    layout->setSpacing(4);
    layout->setContentsMargins({});

    d->mLineEdit = new QLineEdit(this);
    d->mLineEdit->setClearButtonEnabled(true);
    KLineEditEventHandler::catchReturnKey(d->mLineEdit);

    layout->addWidget(d->mLineEdit, 1);

    auto button = new QPushButton(this);
    button->setIcon(QIcon::fromTheme(QStringLiteral("help-contents")));
    button->setFixedHeight(d->mLineEdit->sizeHint().height());
    button->setToolTip(i18nc("@info:tooltip", "Open Address Book"));
    layout->addWidget(button);

    connect(button, &QPushButton::clicked, this, [this]() {
        d->slotAddressBook();
    });
    connect(d->mLineEdit, &QLineEdit::textChanged, this, &EmailAddressRequester::textChanged);
}

EmailAddressRequester::~EmailAddressRequester() = default;

void EmailAddressRequester::clear()
{
    d->mLineEdit->clear();
}

void EmailAddressRequester::setText(const QString &text)
{
    d->mLineEdit->setText(text);
}

QString EmailAddressRequester::text() const
{
    return d->mLineEdit->text();
}

QLineEdit *EmailAddressRequester::lineEdit() const
{
    return d->mLineEdit;
}

#include "moc_emailaddressrequester.cpp"
