/*
 * This file is part of KMail.
 * SPDX-FileCopyrightText: 2009 Constantin Berzan <exit3219@gmail.com>
 *
 * Parts based on KMail code by:
 * Various authors.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "attachmentcontroller.h"

#include "attachmentmodel.h"
#include "attachmentpart.h"
#include "attachmentview.h"
#include "editor/composerwindow.h"
#include "editor_debug.h"

#include "identity/identity.h"
#include <KContacts/Addressee>
#include <KMime/Message>
#include <Libkleo/KeyCache>
#include <MimeTreeParserWidgets/MessageViewerDialog>

#include <QGpgME/Protocol>

using namespace MessageCore;

AttachmentController::AttachmentController(MessageComposer::AttachmentModel *model, AttachmentView *view, ComposerWindow *composer)
    : AttachmentControllerBase(model, composer, composer->actionCollection())
    , mComposer(composer)
    , mView(view)
{
    connect(composer, &ComposerWindow::identityChanged, this, &AttachmentController::identityChanged);

    connect(view, &AttachmentView::contextMenuRequested, this, &AttachmentControllerBase::showContextMenu);
    connect(view->selectionModel(), &QItemSelectionModel::selectionChanged, this, &AttachmentController::selectionChanged);
    connect(view, &QAbstractItemView::doubleClicked, this, &AttachmentController::doubleClicked);

    connect(this, &AttachmentController::refreshSelection, this, &AttachmentController::selectionChanged);

    connect(this, &AttachmentController::showAttachment, this, &AttachmentController::onShowAttachment);
    connect(this, &AttachmentController::selectedAllAttachment, this, &AttachmentController::slotSelectAllAttachment);
    connect(this, &AttachmentController::actionsCreated, this, &AttachmentController::slotActionsCreated);
}

AttachmentController::~AttachmentController() = default;

void AttachmentController::slotSelectAllAttachment()
{
    mView->selectAll();
}

void AttachmentController::identityChanged()
{
    const KIdentityManagementCore::Identity &identity = mComposer->identity();

    // "Attach public key" is only possible if OpenPGP support is available:
    enableAttachPublicKey(QGpgME::openpgp());

    // "Attach my public key" is only possible if OpenPGP support is
    // available and the user specified his key for the current identity:
    enableAttachMyPublicKey(QGpgME::openpgp() && !identity.pgpEncryptionKey().isEmpty());
}

void AttachmentController::attachMyPublicKey()
{
    const KIdentityManagementCore::Identity &identity = mComposer->identity();
    qCDebug(EDITOR_LOG) << identity.identityName();
    auto keyCache = Kleo::KeyCache::instance();
    const auto encryptionKey = identity.pgpEncryptionKey();
    auto key = keyCache->findByFingerprint(encryptionKey.data());
    exportPublicKey(key);
}

void AttachmentController::slotActionsCreated()
{
    // Disable public key actions if appropriate.
    identityChanged();

    // Disable actions like 'Remove', since nothing is currently selected.
    selectionChanged();
}

void AttachmentController::selectionChanged()
{
    const QModelIndexList selectedRows = mView->selectionModel()->selectedRows();
    AttachmentPart::List selectedParts;
    selectedParts.reserve(selectedRows.count());
    for (const QModelIndex &index : selectedRows) {
        auto part = mView->model()->data(index, MessageComposer::AttachmentModel::AttachmentPartRole).value<AttachmentPart::Ptr>();
        selectedParts.append(part);
    }
    setSelectedParts(selectedParts);
}

void AttachmentController::onShowAttachment(KMime::Content *content)
{
    if (content->bodyAsMessage()) {
        KMime::Message::Ptr message(new KMime::Message);
        message->setContent(content->bodyAsMessage()->encodedContent());
        message->parse();

        auto dialog = new MimeTreeParser::Widgets::MessageViewerDialog({message});
        dialog->setAttribute(Qt::WA_DeleteOnClose);
        dialog->show();
    }
}

void AttachmentController::doubleClicked(const QModelIndex &itemClicked)
{
    if (!itemClicked.isValid()) {
        qCDebug(EDITOR_LOG) << "Received an invalid item clicked index";
        return;
    }
    // The itemClicked index will contain the column information. But we want to retrieve
    // the AttachmentPart, so we must recreate the QModelIndex without the column information
    const QModelIndex &properItemClickedIndex = mView->model()->index(itemClicked.row(), 0);
    auto part = mView->model()->data(properItemClickedIndex, MessageComposer::AttachmentModel::AttachmentPartRole).value<AttachmentPart::Ptr>();

    // We can't edit encapsulated messages, but we can view them.
    if (part->isMessageOrMessageCollection()) {
        viewAttachment(part);
    }
}

#include "moc_attachmentcontroller.cpp"
