#include "EmailListModel.h"
#include <QDebug>
#include <QDateTime>

EmailListModel::EmailListModel(QObject *parent)
    : QAbstractTableModel(parent)
{
    refresh();
}

int EmailListModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_emails.size();
}

int EmailListModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return ColCount;
}

QVariant EmailListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_emails.size())
        return QVariant();

    const MailItem& item = m_emails.at(index.row());

    switch (role) {
    case Qt::DisplayRole:
    case Qt::EditRole:
        switch (index.column()) {
        case ColSubject:
            return item.subject();
        case ColSender:
            return item.sender();
        case ColDate:
            return item.date();
        }
        break;
    case IdRole:
        return item.id();
    case SubjectRole:
        return item.subject();
    case SenderRole:
        return item.sender();
    case RecipientRole:
        return item.recipient();
    case DateRole:
        return item.date();
    case ReadRole:
        return item.isRead();
    case FlaggedRole:
        return item.isFlagged();
    case AttachmentsRole:
        return QVariant::fromValue(item.attachments());
    case FileIdRole:
        return item.fileId();
    case SizeRole:
        return item.size();
    case MessageIdRole:
        return item.messageId();
    case SenderInitialRole: {
        QString sender = item.sender();
        if (sender.isEmpty())
            return QString();
        return QString(sender.at(0)).toUpper();
    }
    default:
        return QVariant();
    }
    return QVariant();
}

QVariant EmailListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
        return QVariant();

    switch (section) {
    case ColSubject:
        return tr("Asunto");
    case ColSender:
        return tr("De");
    case ColDate:
        return tr("Fecha");
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> EmailListModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[IdRole] = "id";
    roles[SubjectRole] = "subject";
    roles[SenderRole] = "sender";
    roles[RecipientRole] = "recipient";
    roles[DateRole] = "date";
    roles[ReadRole] = "read";
    roles[FlaggedRole] = "flagged";
    roles[AttachmentsRole] = "attachments";
    roles[FileIdRole] = "fileId";
    roles[SizeRole] = "size";
    roles[MessageIdRole] = "messageId";
    roles[SenderInitialRole] = "senderInitial";
    return roles;
}

void EmailListModel::setFolderId(int folderId)
{
    if (m_folderId == folderId)
        return;
    m_folderId = folderId;
    refresh();
}

void EmailListModel::refresh()
{
    beginResetModel();
    QVector<MailItem> allEmails;
    if (m_folderId == -1) {
        allEmails = MailItemDao::findAll();
    } else {
        allEmails = MailItemDao::findByFolderId(m_folderId);
    }
    
    // Apply filters
    m_emails.clear();
    for (const auto &item : allEmails) {
        // Search filter
        if (!m_searchFilter.isEmpty()) {
            if (!item.subject().contains(m_searchFilter, Qt::CaseInsensitive) &&
                !item.sender().contains(m_searchFilter, Qt::CaseInsensitive) &&
                !item.recipient().contains(m_searchFilter, Qt::CaseInsensitive) &&
                !item.bodyHtml().contains(m_searchFilter, Qt::CaseInsensitive)) {
                continue;
            }
        }
        
        // Unread only
        if (m_unreadOnly && item.isRead()) {
            continue;
        }
        
        // Flagged only
        if (m_flaggedOnly && !item.isFlagged()) {
            continue;
        }
        
        // Has attachments
        if (m_hasAttachments && item.attachments().isEmpty()) {
            continue;
        }
        
        m_emails.append(item);
    }
    endResetModel();
    qDebug() << "EmailListModel refreshed with" << m_emails.size() << "emails for folderId" << m_folderId;
}

void EmailListModel::setSearchFilter(const QString &filter)
{
    if (m_searchFilter == filter)
        return;
    m_searchFilter = filter;
    refresh();
}

void EmailListModel::setShowUnreadOnly(bool show)
{
    if (m_unreadOnly == show)
        return;
    m_unreadOnly = show;
    refresh();
}

void EmailListModel::setShowFlaggedOnly(bool show)
{
    if (m_flaggedOnly == show)
        return;
    m_flaggedOnly = show;
    refresh();
}

void EmailListModel::setShowHasAttachments(bool show)
{
    if (m_hasAttachments == show)
        return;
    m_hasAttachments = show;
    refresh();
}