/*
   SPDX-FileCopyrightText: 2025-2026 Laurent Montel <montel@kde.org>

   SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "textautogenerateattachmentdelegatehelperfile.h"
#include "widgets/common/textautogeneratetextopenfilejob.h"
#include "widgets/view/textautogeneratedelegateutils.h"
#include <KIconLoader>
#include <QMimeDatabase>
#include <QPainter>
#include <QPixmap>
#include <TextAutoGenerateText/TextAutoGenerateAttachment>
#include <TextAutoGenerateText/TextAutoGenerateMessage>
#include <TextAutoGenerateText/TextAutoGenerateMessagesModel>

using namespace TextAutoGenerateText;
using namespace Qt::Literals::StringLiterals;
TextAutoGenerateAttachmentDelegateHelperFile::TextAutoGenerateAttachmentDelegateHelperFile(TextAutoGenerateText::TextAutoGenerateManager *manager,
                                                                                           QObject *parent)
    : TextAutoGenerateAttachmentDelegateHelperBase{manager, parent}
{
}

TextAutoGenerateAttachmentDelegateHelperFile::~TextAutoGenerateAttachmentDelegateHelperFile() = default;

// Icon + text
void TextAutoGenerateAttachmentDelegateHelperFile::draw(const TextAutoGenerateText::TextAutoGenerateAttachment &msgAttach,
                                                        QPainter *painter,
                                                        QRect attachmentsRect,
                                                        [[maybe_unused]] const QModelIndex &index,
                                                        const QStyleOptionViewItem &option) const
{
    const FileLayout layout = doLayout(msgAttach, option, attachmentsRect.width());
    const TextAutoGenerateMessage::Sender sender = index.data(TextAutoGenerateMessagesModel::SenderRole).value<TextAutoGenerateMessage::Sender>();
    const bool isUser = (sender == TextAutoGenerateMessage::Sender::User);
    const int indent = isUser ? TextAutoGenerateDelegateUtils::marginText() : TextAutoGenerateDelegateUtils::leftLLMIndent();

    painter->drawPixmap(attachmentsRect.bottomLeft().x() + indent, attachmentsRect.bottomLeft().y(), layout.pixmap);

    const QFont oldFont = painter->font();
    const QFontMetrics fontMetrics(oldFont);
    const int defaultCharHeight = attachmentsRect.bottomLeft().y() + fontMetrics.ascent();
    painter->drawText(attachmentsRect.bottomLeft().x() + indent + layout.pixmap.size().width() + TextAutoGenerateDelegateUtils::spacingText(),
                      defaultCharHeight,
                      layout.name);
}

QSize TextAutoGenerateAttachmentDelegateHelperFile::sizeHint(const TextAutoGenerateText::TextAutoGenerateAttachment &msgAttach,
                                                             [[maybe_unused]] const QModelIndex &index,
                                                             int maxWidth,
                                                             const QStyleOptionViewItem &option) const
{
    const FileLayout layout = doLayout(msgAttach, option, maxWidth);

    return {layout.nameSize.width() + layout.pixmap.width(), // should be qMax of all sizes, but doesn't really matter
            layout.pixmap.height()};
}

bool TextAutoGenerateAttachmentDelegateHelperFile::handleMouseEvent(const TextAutoGenerateAttachment &msgAttach,
                                                                    QMouseEvent *mouseEvent,
                                                                    QRect attachmentsRect,
                                                                    const QStyleOptionViewItem &option,
                                                                    const QModelIndex &index)
{
    const QEvent::Type eventType = mouseEvent->type();
    switch (eventType) {
    case QEvent::MouseButtonRelease: {
        const QPoint pos = mouseEvent->pos();
        // const FileLayout layout = doLayout(msgAttach, option, attachmentsRect.width());
        if (attachmentsRect.contains(pos)) {
            const auto attachmentId = msgAttach.attachmentId();
            if (!attachmentId.isEmpty()) {
                qDebug() << " Click on file " << msgAttach;
                handleDownloadClicked(const_cast<QWidget *>(option.widget), attachmentId);
                return true;
            }
            qDebug() << " Click on file " << msgAttach;
        }
        break;
    }
    default:
        break;
    }
    return TextAutoGenerateAttachmentDelegateHelperBase::handleMouseEvent(msgAttach, mouseEvent, attachmentsRect, option, index);
}

QPoint TextAutoGenerateAttachmentDelegateHelperFile::adaptMousePosition(const QPoint &pos,
                                                                        const TextAutoGenerateAttachment &msgAttach,
                                                                        QRect attachmentsRect,
                                                                        const QStyleOptionViewItem &option)
{
    // TODO
    return pos;
}

TextAutoGenerateAttachmentDelegateHelperFile::FileLayout
TextAutoGenerateAttachmentDelegateHelperFile::doLayout(const TextAutoGenerateText::TextAutoGenerateAttachment &msgAttach,
                                                       const QStyleOptionViewItem &option,
                                                       [[maybe_unused]] int attachmentsWidth) const
{
    FileLayout layout;
    layout.mimetype = msgAttach.mimeType();
    layout.name = msgAttach.name();
    // TODO cache it.
    const QMimeDatabase db;
    const QMimeType mimeType = db.mimeTypeForName(QString::fromLatin1(layout.mimetype));
    const QString mimeTypeIconName = mimeType.iconName();
    // qDebug() << " mimeTypeIconName " << mimeTypeIconName;
    // qDebug() << " layout.name " << layout.name;
    const QString mimeTypeIconPath = KIconLoader::global()->iconPath(mimeTypeIconName, KIconLoader::Small);
    const QPixmap pix(mimeTypeIconPath);

    // qDebug() << " mimeTypeIconPath " << mimeTypeIconPath;
    const QPixmap scaledPixmap = pix.scaled(18, 18, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    layout.pixmap = scaledPixmap;

    layout.nameSize = option.fontMetrics.size(Qt::TextSingleLine, layout.name);
    return layout;
}

void TextAutoGenerateAttachmentDelegateHelperFile::handleDownloadClicked(QWidget *widget, const QByteArray &attachmentId)
{
    auto job = new TextAutoGenerateText::TextAutoGenerateTextOpenFileJob(mManager, this);
    job->setAttachmentId(attachmentId);
    job->setParentWidget(widget);
    job->start();
}

#include "moc_textautogenerateattachmentdelegatehelperfile.cpp"
