#include "maillist.h"

#include <QPen>
#include <QHeaderView>
#include <QDebug>


MailListItemDelegate::MailListItemDelegate(QObject *parent):
    QAbstractItemDelegate(parent)
{
    rowHeight = 40;
}

MailListItemDelegate::~MailListItemDelegate()
{

}

void MailListItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    QIcon ic = QIcon(qvariant_cast<QPixmap>(index.data(Qt::DecorationRole)));
    QString title = index.data(Qt::DisplayRole).toString();
    QString description = index.data(Qt::UserRole).toString();
    bool bolden_normal = index.data(Qt::UserRole + 2).toBool();

    int imageSpace = 0;

    if (detailedRendering)
    {
        imageSpace = 10;
    }
    else
    {
        imageSpace = 5;
    }

    QRect r = option.rect;

    QRect widget_rect = option.rect;
/*
    QPen penText(currentThemePalette().text(), 1, Qt::SolidLine);
    QPen penItemSeparator(currentThemePalette().text(), 1, Qt::DotLine);

    QFont fontHeadingNormal(currentFont(), 10, QFont::Normal);
    QFont fontDescriptionNormal(currentFont(), 9, QFont::Normal);
    QFont fontHeadingBold(currentFont(), 10, QFont::Bold);
    QFont fontDescriptionBold(currentFont(), 9, QFont::Bold);

    if (option.state & QStyle::State_Selected)
    {

        painter->fillRect(widget_rect, currentThemePalette().highlight());
    }
    else
    {
        painter->fillRect(widget_rect, currentThemePalette().window());
    }

    if (!ic.isNull())
    {
        if (detailedRendering)
        {
            QRect image_rect = option.rect.adjusted(5, 10, -10, -10);
            ic.paint(painter, image_rect, Qt::AlignVCenter | Qt::AlignLeft);

            imageSpace = 55;
        }
        else
        {
            QRect image_rect = option.rect.adjusted(5, 5, -10, -5);
            ic.paint(painter, image_rect, Qt::AlignVCenter | Qt::AlignLeft);

            imageSpace = 40;
        }
    }

    if (bolden_normal && !(option.state & QStyle::State_Selected))
    {
        painter->setFont(fontHeadingNormal);
    }
    else
    {
        painter->setFont(fontHeadingBold);
    }

    if (detailedRendering)
    {
        r = option.rect.adjusted(imageSpace, 0, -10, -30);
        painter->setPen(penText);
        painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignBottom | Qt::AlignLeft, title, &r);
    }
    else
    {
        r = option.rect.adjusted(imageSpace, 10, -10, -15);
        painter->setPen(penText);
        painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignVCenter | Qt::AlignLeft, title, &r);
    }

    r = option.rect.adjusted(imageSpace, 30, -10, 0);

    if (bolden_normal && !(option.state & QStyle::State_Selected))
    {
        painter->setFont(fontDescriptionNormal);
    }
    else
    {
        painter->setFont(fontDescriptionBold);
    }

    if (detailedRendering)
    {
        painter->setPen(penText);
        painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignLeft, description, &r);
    }

    painter->setPen(penItemSeparator);
    painter->drawLine(widget_rect.left(), widget_rect.bottom(), widget_rect.left() + widget_rect.width(), widget_rect.bottom());
*/
}

QSize MailListItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    return QSize(200, rowHeight);
}







MailList::MailList(QWidget *parent) :
    QTreeView(parent)
{

    QStringList headers;
    headers << tr("Title") << tr("Description") << tr("Cantidad") << tr("Cantidad total") << tr("Unidad") << tr("Precio Unitario")
            << tr("Precio Total") << tr("Ganacia") << tr("Precio Total") << tr("Precio Total Venta");

    //TreeModel *model = new TreeModel(headers, file.readAll());
    //setModel(model);

    //connect(this, &QListWidget::itemClicked, this, &MailList::eventMailSelected);
    connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
            this,
            //SLOT(handleSelectionChanged(QItemSelection))
            SLOT(eventMailSelected(QItemSelection))
            );
}

MailList::~MailList()
{

}

/*
void MailList::Initialize(MailView* ptr)
{
    mailViewPtr = ptr;
}
*/

void MailList::eventMailSelected(QItemSelection &selection)
{
    // TODO: chequear esto:
    if(selection.indexes().isEmpty())
    {
        return;
    }
    else if(selection.indexes().size() == 1)
    {
        QModelIndex index = selection.indexes().at(0);

        //Person tp = index.data().value<Person>();
        //actualID = QString::number(tp.id());
        //ui->rightContent->setContactID(actualID);

        //if(ui->rigthContent->currentIndex() != 1)
        //    ui->rigthContent->setCurrentIndex(1);
    }
    else
    {
        //ui->infoWidget->setType(axtMultiple);
        //ui->rigthContent->setCurrentIndex(0);
    }

    /*
    currentViewItem = selection;

    QString currUID = currentViewItem->data(Qt::UserRole + 1).toString();

    if (mailLookup.find(currUID) != mailLookup.end())
    {
        if (mailViewPtr != nullptr)
        {
            currentToken = mailLookup[currUID];
            emit MailSelected(currentToken);
            item->setData(Qt::UserRole + 2, QVariant(false));
            update();
        }
    }
    */
}

void MailList::eventClearMailView()
{
    //clear();
    mailLookup.clear();
    currentViewItem = nullptr;
}

void MailList::eventMailListReceived(QVector<MailHeader>& mlist)
{
    //clear();
    mailLookup.clear();
    currentViewItem = nullptr;

    int count = mlist.size();

    for (int index = 0; index < count; index++)
    {
        HeaderReceived(mlist[index]);
    }
}

///TODO: que es esto??
void MailList::HeaderReceived(MailHeader emlhdr)
{
    QString temp_timestamp = emlhdr.GetTimeStamp();
    //QDateTime dateTime = QDateTime::fromString("ddd, dd MMM YYYY");

    size_t tz_str_pos = -1;

    tz_str_pos = temp_timestamp.indexOf('+');

    if (tz_str_pos == -1)
    {
        tz_str_pos = temp_timestamp.indexOf('-');
    }

    if (tz_str_pos != -1)
    {
        temp_timestamp = temp_timestamp.remove(tz_str_pos, temp_timestamp.length() - tz_str_pos);
    }

    if (mailLookup.find(emlhdr.GetMessageId()) == mailLookup.end())
    {
        QString subject = emlhdr.GetSubject();
        if (subject.toLower().contains("utf-8"))
        {
            subject = emlhdr.GetSubject();
        }

        QString description;
        description += emlhdr.GetFrom();
        description += ", ";
        description += temp_timestamp;

        //QItemSelection* mailItem = new QItemSelection(this);
        //mailItem->setData(Qt::DisplayRole, QVariant(subject));
        //mailItem->setData(Qt::UserRole, QVariant(description));
        //mailItem->setData(Qt::UserRole + 1, QVariant(emlhdr.GetHeaderValue("UID")));

        mailLookup[emlhdr.GetHeaderValue("UID")] = emlhdr;
    }
}

void MailList::DeleteCurrent()
{
    if (currentViewItem == nullptr)
    {
        return;
    }

    QString currUID;// = currentViewItem->data(Qt::UserRole + 1).toString();

    if (mailLookup.find(currUID) != mailLookup.end())
    {
        if (mailViewPtr != nullptr)
        {
            currentToken = mailLookup[currUID];
        }
    }
/*
    if (mailClientPtr->RemoveEmail(currentToken.GetHeaderValue("Account"), currentToken.GetHeaderValue("Directory"), currentToken.GetHeaderValue("UID"), currentToken.GetMessageId()))
    {
        removeItemWidget(currentViewItem);
        delete currentViewItem;
        currentViewItem = nullptr;
    }
    */
}

void MailList::FlagCurrent()
{
    if (currentViewItem == nullptr)
    {
        return;
    }

    QString currUID;// = currentViewItem->data(Qt::UserRole + 1).toString();

    if (mailLookup.find(currUID) != mailLookup.end())
    {
        if (mailViewPtr != nullptr)
        {
            currentToken = mailLookup[currUID];
        }
    }

    QString flag = "Flagged";

//	if (mailClientPtr->FlagEmail(currentToken.GetHeaderValue("Account"), currentToken.GetHeaderValue("Directory"), currentToken.GetHeaderValue("UID"), flag))
    {

    }
}

void MailList::MarkAsSeenCurrent()
{
    if (currentViewItem == nullptr)
    {
        return;
    }

    QString currUID;// = currentViewItem->data(Qt::UserRole + 1).toString();

    if (mailLookup.find(currUID) != mailLookup.end())
    {
        if (mailViewPtr != nullptr)
        {
            currentToken = mailLookup[currUID];
        }
    }

//	mailClientPtr->MarkEmailSeen(currentToken.GetHeaderValue("Account"), currentToken.GetHeaderValue("Directory"), currentToken.GetHeaderValue("UID"));
}

void MailList::MoveToNext()
{
    if (currentViewItem == nullptr)
    {
        return;
    }
}

void MailList::MoveToPrevious()
{
    if (currentViewItem == nullptr)
    {
        return;
    }
}

MailHeader MailList::GetCurrentToken()
{
    return currentToken;
}

void MailList::resizeEvent(QResizeEvent *event)
{

    qDebug() << width();


    if(width() > 400)
    {
        header()->show();
        QTreeView::resizeEvent(event);
        return;
    }

    header()->hide();
    QTreeView::resizeEvent(event);

}
