// Squawk messenger.
// Copyright (C) 2019  Yury Gubich <blue@macaw.me>
//
// 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 3 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, see <http://www.gnu.org/licenses/>.

#ifndef DIALOGQUEUE_H
#define DIALOGQUEUE_H

#include <QObject>
#include <QInputDialog>
#include <QMainWindow>

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>

#include <ui/widgets/accounts/credentialsprompt.h>
#include <ui/models/roster.h>

class DialogQueue : public QObject
{
    Q_OBJECT
public:
    enum Action {
        none,
        askPassword,
        askCredentials
    };

    DialogQueue(const Models::Roster& roster);
    ~DialogQueue();

    bool addAction(const QString& source, Action action);
    bool cancelAction(const QString& source, Action action);

signals:
    void modifyAccountRequest(const QString&, const QMap<QString, QVariant>&);
    void responsePassword(const QString& account, const QString& password);
    void disconnectAccount(const QString&);

public:
    void setParentWidnow(QMainWindow* parent);
    void quit();

private:
    void performNextAction();
    void actionDone();

private slots:
    void onPropmtAccepted();
    void onPropmtRejected();

private:
    QString currentSource;
    Action currentAction;

    struct ActionId {
    public:
        ActionId(const QString& p_source, Action p_action);
        ActionId(const ActionId& other);

        const QString source;
        const Action action;

        bool operator < (const ActionId& other) const;
    };

    typedef boost::multi_index_container <
        ActionId,
        boost::multi_index::indexed_by <
            boost::multi_index::ordered_unique <
                boost::multi_index::identity <ActionId>
            >,
            boost::multi_index::sequenced<>
        >
    > Queue;

    typedef Queue::nth_index<0>::type Collection;
    typedef Queue::nth_index<1>::type Sequence;

    Queue queue;
    Collection& collection;
    Sequence& sequence;

    QDialog* prompt;
    QMainWindow* parent;
    const Models::Roster& roster;
};

#endif // DIALOGQUEUE_H