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

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

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

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 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();
        // Get first character, or first non-space character?
        // Simple: first character of the sender string
        return QString(sender.at(0)).toUpper();
    }
    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();
    if (m_folderId == -1) {
        m_emails = MailItemDao::findAll();
    } else {
        m_emails = MailItemDao::findByFolderId(m_folderId);
    }
    endResetModel();
    qDebug() << "EmailListModel refreshed with" << m_emails.size() << "emails for folderId" << m_folderId;
}