/*
 *   This file is part of Dianara
 *   Copyright 2012-2019  JanKusanagi JRR <jancoding@gmx.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA .
 */

#include "userposts.h"


UserPosts::UserPosts(QString userId, QString userName,
                     QIcon userAvatar, QString userOutbox,
                     PumpController *pumpController,
                     GlobalObject *globalObject,
                     FilterChecker *filterChecker,
                     QWidget *parent) : QWidget(parent)
{
    m_pumpController = pumpController;
    m_globalObject = globalObject;
    connect(m_globalObject, &GlobalObject::programShuttingDown,
            this, &QWidget::close);

    this->setWindowFlags(Qt::Window);
    this->setWindowModality(Qt::NonModal);

    m_timelineTitle = tr("Posts by %1").arg(userName);
    this->setWindowTitle(m_timelineTitle + " - Dianara");
    this->setWindowIcon(userAvatar);
    this->setMinimumSize(200, 300);

    QSettings settings;
    this->resize(settings.value("UserTimeline/userTimelineSize",
                                QSize(560, 720)).toSize());

    m_timeline = new TimeLine(PumpController::UserTimelineRequest,
                              m_pumpController,
                              m_globalObject,
                              filterChecker,
                              this);

    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setContentsMargins(1, 1, 1, 1);
    m_scrollArea->setWidget(m_timeline);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setFrameStyle(QFrame::Box | QFrame::Raised);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    connect(m_timeline, &TimeLine::scrollTo,
            this, &UserPosts::scrollTimelineTo);


    m_infoLabel = new QLabel(tr("Loading..."), this);
    m_infoLabel->setTextFormat(Qt::RichText);

    m_closeButton = new QPushButton(QIcon::fromTheme("window-close",
                                                     QIcon(":/images/button-close.png")),
                                    tr("&Close"),
                                    this);
    connect(m_closeButton, &QAbstractButton::clicked,
            this, &QWidget::close);

    // PumpController's connections
    connect(m_pumpController, &PumpController::userTimelineReceived,
            this, &UserPosts::fillTimeLine);
    connect(m_pumpController, &PumpController::userTimelineFailed,
            this, &UserPosts::onTimelineFailed);
    connect(m_pumpController, &PumpController::commentsReceived,
            m_timeline, &TimeLine::setCommentsInPost);

    connect(m_timeline, &TimeLine::timelineRendered,
            this, &UserPosts::notifyTimelineUpdate);

    // Initial load
    m_timeline->setCustomUrl(userOutbox);
    m_timeline->setDisabled(true);
    m_timeline->clearTimeLineContents(); // Hack to get comments properly resized
    // FIXME: On first load, should set showMessage=false so initial "Requesting..." is not erased
    // Not doing that for 1.3.1 due to problems

    m_pumpController->getFeed(PumpController::UserTimelineRequest,
                              m_globalObject->getPostsPerPageMain(),
                              userOutbox);



    // First part of message shown at the bottom
    m_userInfoString = userName + " - " + userId;


    // Layout
    m_bottomLayout = new QHBoxLayout();
    m_bottomLayout->addWidget(m_infoLabel);
    m_bottomLayout->addStretch(1);
    m_bottomLayout->addWidget(m_closeButton);

    m_mainLayout = new QVBoxLayout();
    m_mainLayout->setContentsMargins(2, 2, 2, 2);
    m_mainLayout->addWidget(m_scrollArea);
    m_mainLayout->addSpacing(6);
    m_mainLayout->addLayout(m_bottomLayout);
    this->setLayout(m_mainLayout);

    qDebug() << "UserPosts timeline container created for" << userName;
}

UserPosts::~UserPosts()
{
    qDebug() << "UserPosts timeline container destroyed";
}


//////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// SLOTS //////////////////////////////////
//////////////////////////////////////////////////////////////////////////////


/*
 * Set contents of timeline only if the user timeline received matches this one.
 * Necessary when opening a user's timeline from another user's timeline
 *
 */
void UserPosts::fillTimeLine(QVariantList postList, QString previousLink,
                             QString nextLink, int totalItems, QString url)
{
    if (m_timelineUrl.isEmpty()) // Set it the first time
    {
        m_timelineUrl = url;
    }

    if (url == m_timelineUrl)
    {
        m_timeline->setTimeLineContents(postList, previousLink,
                                        nextLink, totalItems);
    }
}



void UserPosts::notifyTimelineUpdate()
{
    const QString message = tr("Received '%1'.").arg(m_timelineTitle);
    m_globalObject->setStatusMessage(message);
    m_globalObject->logMessage(message);

    QString postCount = QLocale::system().toString(m_timeline->getTotalPosts());
    m_infoLabel->setText(m_userInfoString
                         + " &mdash; " //// Long dash
                         + tr("%1 posts").arg(postCount));

    m_timeline->resizePosts(QList<Post *>(), true); // Resize all posts
}


// Set error messages if timeline fails to load
void UserPosts::onTimelineFailed()
{
    const QString message = tr("Error loading the timeline");
    m_infoLabel->setText(message + ".");
    m_timeline->showMessage(message);
}


// React to Control+PgUp/PgDn, etc. sent from TimeLine()
void UserPosts::scrollTimelineTo(QAbstractSlider::SliderAction sliderAction)
{
    m_scrollArea->verticalScrollBar()->triggerAction(sliderAction);
}


//////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// PROTECTED ////////////////////////////////
//////////////////////////////////////////////////////////////////////////////


void UserPosts::resizeEvent(QResizeEvent *event)
{
    m_timeline->resizePosts(QList<Post *>(), true); // resizeAll=true

    event->accept();
}


void UserPosts::closeEvent(QCloseEvent *event)
{
    QSettings settings;
    if (settings.isWritable())
    {
        settings.setValue("UserTimeline/userTimelineSize",
                          this->size());
    }

    delete m_timeline;
    this->deleteLater();

    this->hide();
    event->ignore();
}


void UserPosts::keyPressEvent(QKeyEvent *event)
{
    // ESC to close, if there are no comments in progress
    if (event->key() == Qt::Key_Escape
     && !m_timeline->commentingOnAnyPost())
    {
        event->accept();
        this->close();
    }
    else
    {
        event->ignore();
    }
}
