/*
 *   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 "audienceselector.h"

AudienceSelector::AudienceSelector(PumpController *pumpController,
                                   QString selectorType,
                                   QWidget *parent) : QFrame(parent)
{
    this->selectorType = selectorType;

    QString titlePart;
    if (this->selectorType == "to")
    {
        titlePart = tr("'To' List");
    }
    else
    {
        titlePart = tr("'Cc' List");
    }

    this->setWindowTitle(titlePart + " - Dianara");
    this->setWindowIcon(QIcon::fromTheme("system-users",
                                         QIcon(":/images/no-avatar.png")));
    this->setWindowFlags(Qt::Dialog);
    this->setWindowModality(Qt::WindowModal);
    this->setMinimumSize(440, 340);

    QSettings settings;
    QSize savedWindowsize = settings.value("AudienceSelector/"
                                           "audienceWindowSize").toSize();
    if (savedWindowsize.isValid())
    {
        this->resize(savedWindowsize);
    }



    // Left side, all contacts, with filter
    this->peopleWidget = new PeopleWidget(tr("&Add to Selected") + " >>",
                                          PeopleWidget::EmbeddedWidget,
                                          pumpController,
                                          this);
    connect(peopleWidget, SIGNAL(contactSelected(QIcon,QString,QString)),
            this, SLOT(copyToSelected(QIcon,QString,QString)));
    connect(peopleWidget, SIGNAL(addButtonPressed(QIcon,QString,QString)),
            this, SLOT(copyToSelected(QIcon,QString,QString)));



    this->allGroupboxLayout = new QVBoxLayout();
    allGroupboxLayout->addWidget(peopleWidget);

    allContactsGroupbox = new QGroupBox(tr("All Contacts"),
                                        this);
    allContactsGroupbox->setLayout(allGroupboxLayout);


    // Right side, selected contacts
    explanationLabel = new QLabel(tr("Select people from the list on the left.\n"
                                     "You can drag them with the mouse, click or "
                                     "double-click on them, or select them and "
                                     "use the button below.",
                                     "ON THE LEFT should change to ON THE "
                                     "RIGHT in RTL languages"),
                                  this);
    explanationLabel->setWordWrap(true);

    selectedListWidget = new QListWidget(this);
    selectedListWidget->setDragDropMode(QListView::DragDrop);
    selectedListWidget->setDefaultDropAction(Qt::MoveAction);
    selectedListWidget->setSelectionMode(QListView::ExtendedSelection);
    selectedListWidget->setIconSize(QSize(48, 48));

    this->clearSelectedListButton = new QPushButton(QIcon::fromTheme("edit-clear-list",
                                                                     QIcon(":/images/button-delete.png")),
                                                    tr("Clear &List"),
                                                    this);
    connect(clearSelectedListButton, SIGNAL(clicked()),
            selectedListWidget, SLOT(clear()));


    doneButton = new QPushButton(QIcon::fromTheme("dialog-ok",
                                                  QIcon(":/images/button-save.png")),
                                 tr("&Done"),
                                 this);
    connect(doneButton, SIGNAL(clicked()),
            this, SLOT(setAudience()));
    cancelButton = new QPushButton(QIcon::fromTheme("dialog-cancel",
                                                    QIcon(":/images/button-cancel.png")),
                                   tr("&Cancel"),
                                   this);
    connect(cancelButton, SIGNAL(clicked()),
            this, SLOT(close()));


    buttonsLayout = new QHBoxLayout();
    buttonsLayout->setAlignment(Qt::AlignRight);
    buttonsLayout->addWidget(doneButton);
    buttonsLayout->addWidget(cancelButton);


    selectedGroupboxLayout = new QVBoxLayout();
    selectedGroupboxLayout->addWidget(explanationLabel);
    selectedGroupboxLayout->addSpacing(12);
    selectedGroupboxLayout->addWidget(selectedListWidget);
    selectedGroupboxLayout->addWidget(clearSelectedListButton);
    selectedGroupboxLayout->addSpacing(8);
    selectedGroupboxLayout->addLayout(buttonsLayout);

    this->selectedListGroupbox = new QGroupBox(tr("Selected People"),
                                               this);
    selectedListGroupbox->setLayout(selectedGroupboxLayout);

    this->mainLayout = new QHBoxLayout();
    mainLayout->addWidget(allContactsGroupbox,  3);
    mainLayout->addWidget(selectedListGroupbox, 4);
    this->setLayout(mainLayout);


    // Ctrl+Enter is the same as the "Done" button
    doneAction = new QAction(this);
    QList<QKeySequence> doneShortcuts;
    doneShortcuts << QKeySequence("Ctrl+Return")
                  << QKeySequence("Ctrl+Enter");
    doneAction->setShortcuts(doneShortcuts);
    connect(doneAction, SIGNAL(triggered()),
            this, SLOT(setAudience()));
    this->addAction(doneAction);

    // ESC is the same as the "Cancel" button
    cancelAction = new QAction(this);
    cancelAction->setShortcut(Qt::Key_Escape);
    connect(cancelAction, SIGNAL(triggered()),
            this, SLOT(close()));
    this->addAction(cancelAction);


    qDebug() << "AudienceSelector created" << titlePart;
}


AudienceSelector::~AudienceSelector()
{
    qDebug() << "AudienceSelector destroyed";
}



/*
 * Reset lists and widgets to default status
 *
 */
void AudienceSelector::resetLists()
{
    this->peopleWidget->resetWidget();

    this->selectedListWidget->clear();
    restoreSelected();
}

void AudienceSelector::deletePrevious()
{
    foreach (QListWidgetItem *item, previousItems)
    {
        delete item;
    }
    previousItems.clear();
}


void AudienceSelector::saveSelected()
{
    qDebug() << "AudienceSelector::saveSelected()";
    // Clear and delete all first
    this->deletePrevious();

    int totalItems = this->selectedListWidget->count();
    for (int counter = 0; counter < totalItems; ++counter)
    {
        this->previousItems.append(selectedListWidget->item(counter)->clone());
    }
}


void AudienceSelector::restoreSelected()
{
    qDebug() << "AudienceSelector::restoreSelected()";
    foreach (QListWidgetItem *item, this->previousItems)
    {
        this->selectedListWidget->addItem(item->clone());
    }
}



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



/*
 * Copy a contact to the list of Selected
 *
 * The contact string comes in a SIGNAL from PeopleWidget
 *
 */
void AudienceSelector::copyToSelected(QIcon contactIcon, QString contactString,
                                      QString contactUrl)
{
    if (!contactString.isEmpty())
    {
        int itemExists = selectedListWidget->findItems(contactString,
                                                       Qt::MatchExactly).size();
        if (itemExists == 0)
        {
            QListWidgetItem *item = new QListWidgetItem(contactIcon,
                                                        contactString);
            item->setData(Qt::UserRole + 1, contactUrl);

            this->selectedListWidget->addItem(item);
        }
        else
        {
            qDebug() << "AudienceSelector::copyToSelected() "
                        "ignoring already added recipient";
        }
    }
}



/*
 * The "Done" button: emit signal with list of selected people
 *
 */
void AudienceSelector::setAudience()
{
    int addressCount = this->selectedListWidget->count();

    QStringList addressList;
    QStringList urlList;
    for (int counter=0; counter < addressCount; ++counter)
    {
        addressList.append(selectedListWidget->item(counter)->text());
        urlList.append(selectedListWidget->item(counter)->data(Qt::UserRole + 1)
                                                         .toString());
    }


    emit audienceSelected(selectorType, addressList, urlList);

    saveSelected();  // To restore the list later, if the dialog is shown again

    this->hide();  // Don't close(), because that resets the lists =)
}



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



void AudienceSelector::closeEvent(QCloseEvent *event)
{
    this->resetLists();
    this->hide();

    event->accept();
}

void AudienceSelector::hideEvent(QHideEvent *event)
{
    QSettings settings;
    if (settings.isWritable())
    {
        settings.setValue("AudienceSelector/audienceWindowSize", this->size());
    }

    event->accept();
}
