/*
 *   This file is part of Dianara
 *   Copyright 2012-2016  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)
{
    this->pController = pumpController;
    this->globalObj = globalObject;

    this->setWindowFlags(Qt::Dialog);
    this->setWindowModality(Qt::WindowModal);

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

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

    timeline = new TimeLine(PumpController::UserTimelineRequest,
                            this->pController,
                            this->globalObj,
                            filterChecker,
                            this);

    this->scrollArea = new QScrollArea(this);
    this->scrollArea->setContentsMargins(1, 1, 1, 1);
    this->scrollArea->setWidget(timeline);
    this->scrollArea->setWidgetResizable(true);
    this->scrollArea->setFrameStyle(QFrame::Box | QFrame::Raised);
    this->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    connect(timeline, SIGNAL(scrollTo(QAbstractSlider::SliderAction)),
            this, SLOT(scrollTimelineTo(QAbstractSlider::SliderAction)));


    this->infoLabel = new QLabel(tr("Loading..."), this);
    this->closeButton = new QPushButton(QIcon::fromTheme("window-close",
                                                         QIcon(":/images/button-close.png")),
                                        tr("&Close"),
                                        this);
    connect(closeButton, SIGNAL(clicked()),
            this, SLOT(close()));

    // PumpController's connections
    connect(pController, SIGNAL(userTimelineReceived(QVariantList,QString,QString,int,QString)),
            this, SLOT(fillTimeLine(QVariantList,QString,QString,int,QString)));
    connect(pController, SIGNAL(userTimelineFailed()),
            this, SLOT(onTimelineFailed()));
    connect(pController, SIGNAL(commentsReceived(QVariantList,QString)),
            timeline, SLOT(setCommentsInPost(QVariantList,QString)));

    connect(timeline, SIGNAL(timelineRendered(PumpController::requestTypes,int,int,int,int,int,int,int)),
            this, SLOT(notifyTimelineUpdate()));

    // Initial load
    this->timeline->setCustomUrl(userOutbox);
    this->timeline->setDisabled(true);
    this->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

    pController->getFeed(PumpController::UserTimelineRequest,
                         this->globalObj->getPostsPerPageMain(),
                         userOutbox);



    // String shown at the bottom
    userInfoString = userName + " - " + userId; // kinda TMP -- FIXME


    // Layout
    this->bottomLayout = new QHBoxLayout();
    bottomLayout->addWidget(infoLabel);
    bottomLayout->addStretch(1);
    bottomLayout->addWidget(closeButton);

    this->mainLayout = new QVBoxLayout();
    mainLayout->setContentsMargins(2, 2, 2, 2);
    mainLayout->addWidget(scrollArea);
    mainLayout->addSpacing(6);
    mainLayout->addLayout(bottomLayout);
    this->setLayout(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 (this->timelineUrl.isEmpty()) // Set it the first time
    {
        this->timelineUrl = url;
    }

    if (url == this->timelineUrl)
    {
        this->timeline->setTimeLineContents(postList, previousLink,
                                            nextLink, totalItems);
    }
}



void UserPosts::notifyTimelineUpdate()
{
    QString message = tr("Received '%1'.").arg(this->timelineTitle);
    this->globalObj->setStatusMessage(message);
    this->globalObj->logMessage(message);

    QString postCount = QLocale::system().toString(timeline->getTotalPosts());
    this->infoLabel->setText(this->userInfoString
                             + " - "
                             + tr("%1 posts").arg(postCount));

    this->timeline->resizePosts(QList<Post *>(), true); // resize all posts
}

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


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


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


void UserPosts::resizeEvent(QResizeEvent *event)
{
    this->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 this->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
     && !this->timeline->commentingOnAnyPost())
    {
        event->accept();
        this->close();
    }
    else
    {
        event->ignore();
    }
}
