/*
 * 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/>.
 */

#include "account.h"
#include <QXmppMessage.h>

#include <QDateTime>

#include "shared/defines.h"

Core::Account::Account(
    const QString& p_login,
    const QString& p_server,
    const QString& p_password,
    const QString& p_name,
    bool p_active,
    NetworkAccess* p_net,
    QObject* parent
):
    QObject(parent),
    name(p_name),
    archiveQueries(),
    client(),
    config(),
    presence(),
    state(Shared::ConnectionState::disconnected),

    mh(new MessageHandler(this)),
    rh(new RosterHandler(this)),
    vh(new VCardHandler(this)),
    dh(new DiscoveryHandler(this)),
#if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 5, 0)
    th(new TrustHandler(this)),
#endif
#ifdef WITH_OMEMO
    oh(new OmemoHandler(this)),
    om(new QXmppOmemoManager(oh)),
#endif
#if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 5, 0)
    tm(new QXmppTrustManager(th)),
    cm(new QXmppCarbonManagerV2()),
    psm(new QXmppPubSubManager()),
#else
    cm(new QXmppCarbonManager()),
#endif
    am(new QXmppMamManager()),
    mm(new QXmppMucManager()),
    bm(new QXmppBookmarkManager()),
    rm(client.findExtension<QXmppRosterManager>()),
    vm(client.findExtension<QXmppVCardManager>()),
    um(new QXmppUploadRequestManager()),
    dm(client.findExtension<QXmppDiscoveryManager>()),
    rcpm(new QXmppMessageReceiptManager()),
    reconnectScheduled(false),
    reconnectTimer(new QTimer),
    network(p_net),
    delay(nullptr),
    passwordType(Shared::AccountPassword::plain),
    lastError(Error::none),
    pepSupport(Shared::Support::unknown),
    active(p_active),
    notReadyPassword(false),
    loadingOmemo(false)
{
    config.setUser(p_login);
    config.setDomain(p_server);
    config.setPassword(p_password);
    config.setAutoAcceptSubscriptions(true);
    // config.setIgnoreSslErrors(true);
    // config.setAutoReconnectionEnabled(false);
    delay = new DelayManager::Manager(getBareJid());
    QObject::connect(delay, &DelayManager::Manager::gotInfo, this, &Account::infoReady);
    QObject::connect(delay, &DelayManager::Manager::gotOwnInfo, this, &Account::infoReady);

    QObject::connect(delay, &DelayManager::Manager::requestOwnVCard, vm, &QXmppVCardManager::requestClientVCard);
    QObject::connect(delay, &DelayManager::Manager::requestVCard, vm, &QXmppVCardManager::requestVCard);

    rh->initialize();
    vh->initialize();
    dh->initialize();
    
    QObject::connect(&client, &QXmppClient::stateChanged, this, &Account::onClientStateChange);
    QObject::connect(&client, &QXmppClient::presenceReceived, this, &Account::onPresenceReceived);
    QObject::connect(&client, &QXmppClient::messageReceived, mh, &MessageHandler::onMessageReceived);
    QObject::connect(&client, &QXmppClient::error, this, &Account::onClientError);
    
    client.addExtension(cm);
    
#if (QXMPP_VERSION) < QT_VERSION_CHECK(1, 5, 0)
    QObject::connect(cm, &QXmppCarbonManager::messageReceived, mh, &MessageHandler::onCarbonMessageReceived);
    QObject::connect(cm, &QXmppCarbonManager::messageSent, mh, &MessageHandler::onCarbonMessageSent);
#endif
    
    client.addExtension(am);
    
    QObject::connect(am, &QXmppMamManager::logMessage, this, &Account::onMamLog);
    QObject::connect(am, &QXmppMamManager::archivedMessageReceived, this, &Account::onMamMessageReceived);
    QObject::connect(am, &QXmppMamManager::resultsRecieved, this, &Account::onMamResultsReceived);
    
    client.addExtension(mm);
    client.addExtension(bm);
    client.addExtension(um);
    QObject::connect(um, &QXmppUploadRequestManager::slotReceived, mh, &MessageHandler::onUploadSlotReceived);
    QObject::connect(um, &QXmppUploadRequestManager::requestFailed, mh, &MessageHandler::onUploadSlotRequestFailed);
    
    QObject::connect(network, &NetworkAccess::uploadFileComplete, mh, &MessageHandler::onUploadFileComplete);
    QObject::connect(network, &NetworkAccess::downloadFileComplete, mh, &MessageHandler::onDownloadFileComplete);
    QObject::connect(network, &NetworkAccess::loadFileError, mh, &MessageHandler::onLoadFileError);
    
    client.addExtension(rcpm);
    QObject::connect(rcpm, &QXmppMessageReceiptManager::messageDelivered, mh, &MessageHandler::onReceiptReceived);

    client.addExtension(psm);

#ifdef WITH_OMEMO
    QObject::connect(delay, &DelayManager::Manager::requestBundles, oh, &OmemoHandler::requestBundles);
    QObject::connect(delay, &DelayManager::Manager::requestOwnBundles, oh, &OmemoHandler::requestOwnBundles);

    QObject::connect(om, &QXmppOmemoManager::deviceAdded, oh, &OmemoHandler::onOmemoDeviceAdded);

    client.addExtension(tm);
    client.addExtension(om);
    om->setSecurityPolicy(QXmpp::Toakafa);

    if (oh->hasOwnDevice()) {
        QXmppTask<bool> future = om->load();
        loadingOmemo = true;
        future.then(this, [this] (bool result) {
            loadingOmemo = false;
            if (state == Shared::ConnectionState::scheduled)
                client.connectToServer(config, presence);

            if (result)
                qDebug() << "successfully loaded OMEMO data for account" << getName();
            else
                qDebug() << "couldn't load OMEMO data for account" << getName();
        });
    }
#endif
    
    reconnectTimer->setSingleShot(true);
    QObject::connect(reconnectTimer, &QTimer::timeout, this, &Account::onReconnectTimer);
    
    if (name == "Test") {
        QXmppLogger* logger = new QXmppLogger(this);
        logger->setLoggingType(QXmppLogger::SignalLogging);
        client.setLogger(logger);

        QObject::connect(logger, &QXmppLogger::message, this, [](QXmppLogger::MessageType type, const QString& text) {
            SHARED_UNUSED(type);
            qDebug() << text;
        });
    }
}

Core::Account::~Account() {
    if (reconnectScheduled) {
        reconnectScheduled = false;
        reconnectTimer->stop();
    }
    
    QObject::disconnect(network, &NetworkAccess::uploadFileComplete, mh, &MessageHandler::onUploadFileComplete);
    QObject::disconnect(network, &NetworkAccess::downloadFileComplete, mh, &MessageHandler::onDownloadFileComplete);
    QObject::disconnect(network, &NetworkAccess::loadFileError, mh, &MessageHandler::onLoadFileError);
    
    rh->clear();    //conferenses inside of roster handler hold QXmppMuc objects.
                    //If we destroy QXmppMucManager, then when we will be destroying RosterHandler
                    //it will try to destory Core::Conference objects
                    //and inside of those QXmppMuc objects will already be destroyed.
                    //So, clear will start the destruction from Core::Conference and this way it's not gonna crash

    delete delay;
    delete reconnectTimer;
    delete rcpm;
    delete um;
    delete bm;
    delete mm;
    delete am;
    delete cm;
#if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 5, 0)
    delete psm;
#endif
#ifdef WITH_OMEMO
    delete om;
    delete tm;
    delete oh;
    delete th;
#endif

    delete dh;
    delete vh;
    delete rh;
    delete mh;
}

Shared::ConnectionState Core::Account::getState() const {
    return state;}

void Core::Account::connect() {
    if (reconnectScheduled) {
        reconnectScheduled = false;
        reconnectTimer->stop();
    }
    if (state == Shared::ConnectionState::disconnected) {
        if (notReadyPassword) {
            emit needPassword();
        } else {
            if (loadingOmemo) {
                state = Shared::ConnectionState::scheduled;
                emit connectionStateChanged(state);
            } else {
                client.connectToServer(config, presence);
            }
        }

    } else {
        qDebug("An attempt to connect an account which is already connected, skipping");
    }
}

void Core::Account::onReconnectTimer() {
    if (reconnectScheduled) {
        reconnectScheduled = false;
        connect();
    }
}

void Core::Account::disconnect() {
    if (reconnectScheduled) {
        reconnectScheduled = false;
        reconnectTimer->stop();
    }
    if (state != Shared::ConnectionState::disconnected) {
        //rh->clearConferences();
        if (state != Shared::ConnectionState::scheduled) {
            client.disconnectFromServer();
        } else {
            state = Shared::ConnectionState::disconnected;
            emit connectionStateChanged(state);
        }
    }
}

void Core::Account::onClientStateChange(QXmppClient::State st) {
    switch (st) {
        case QXmppClient::ConnectedState: {
            if (state != Shared::ConnectionState::connected) {
                if (client.isActive()) {
                    Shared::ConnectionState os = state;
                    state = Shared::ConnectionState::connected;
                    if (os == Shared::ConnectionState::connecting) {
#ifdef WITH_OMEMO
                        if (!oh->hasOwnDevice()) {
                            qDebug() << "setting up OMEMO data for account" << getName();
                            om->changeDeviceLabel(QGuiApplication::applicationDisplayName() + " - " + QSysInfo::productType());
                            QXmppTask<bool> future = om->setUp();
                            future.then(this, [this] (bool result) {
                                if (result)
                                    qDebug() << "successfully set up OMEMO data for account" << getName();
                                 else
                                    qDebug() << "couldn't set up OMEMO data for account" << getName();

                                if (state == Shared::ConnectionState::connected)
                                    runDiscoveryService();

                            });
                        } else {
                            runDiscoveryService();
                        }
#else
                        runDiscoveryService();
#endif
                    }
                    lastError = Error::none;
                    emit connectionStateChanged(state);
                }
            } else {
                qDebug()    << "Something weird happened - xmpp client of account" << name
                            << "reported about successful connection but account was in" << state << "state";
            }
        }
            break;
        case QXmppClient::ConnectingState: {
            if (state != Shared::ConnectionState::connecting) {
                state = Shared::ConnectionState::connecting;
                emit connectionStateChanged(state);
            }
        }
            break;
        case QXmppClient::DisconnectedState: {
            if (state != Shared::ConnectionState::disconnected) {
                handleDisconnection();
                state = Shared::ConnectionState::disconnected;
                emit connectionStateChanged(state);
            } else {
                qDebug()    << "Something weird happened - xmpp client of account" << name
                            << "reported about disconnection but account was in" << state << "state";
            }
        }
            break;
    }
}

void Core::Account::reconnect() {
    if (!reconnectScheduled) {      //TODO define behavior if It was connection or disconnecting
        if (state == Shared::ConnectionState::connected) {
            reconnectScheduled = true;
            reconnectTimer->start(500);
            client.disconnectFromServer();
        } else {
            qDebug() << "An attempt to reconnect account" << getName() << "which was not connected";
        }
    }
}

Shared::Availability Core::Account::getAvailability() const {
    if (state == Shared::ConnectionState::connected) {
        QXmppPresence::AvailableStatusType pres = presence.availableStatusType();
        return static_cast<Shared::Availability>(pres);         //they are compatible;
    } else {
        return Shared::Availability::offline;
    }
}

void Core::Account::setAvailability(Shared::Availability avail) {
    if (avail == Shared::Availability::offline) {
        disconnect();               //TODO not sure how to do here - changing state may cause connection or disconnection
    } else {
        QXmppPresence::AvailableStatusType pres = static_cast<QXmppPresence::AvailableStatusType>(avail);
        
        presence.setAvailableStatusType(pres);
        if (state != Shared::ConnectionState::disconnected)
            client.setClientPresence(presence);
    }
}

void Core::Account::runDiscoveryService() {
    qDebug() << "running service discovery for account" << name;
    dm->requestItems(getServer());
    dm->requestInfo(getServer());
}

void Core::Account::onPresenceReceived(const QXmppPresence& p_presence) {
    QString id = p_presence.from();
    QStringList comps = id.split("/");
    QString jid = comps.front().toLower();
    QString resource = comps.back();
    
    if (jid == getBareJid()) {
        if (resource == getResource())
            emit availabilityChanged(static_cast<Shared::Availability>(p_presence.availableStatusType()));

        vh->handlePresenceOfMyAccountChange(p_presence);
    } else {
        RosterItem* item = rh->getRosterItem(jid);
        if (item != nullptr) {
            if (item->isMuc())  //MUC presence is handled by inner muc events
                return;
            else
                item->handlePresence(p_presence);
        }
    }
    
    switch (p_presence.type()) {
        case QXmppPresence::Error:
            qDebug() << "An error reported by presence from" << id << p_presence.error().text();
            break;
        case QXmppPresence::Available: {
            QDateTime lastInteraction = p_presence.lastUserInteraction();
            if (!lastInteraction.isValid())
                lastInteraction = QDateTime::currentDateTimeUtc();

            emit addPresence(jid, resource, {
                {"lastActivity", lastInteraction},
                {"availability", p_presence.availableStatusType()},           //TODO check and handle invisible
                {"status", p_presence.statusText()},
                {"client", QVariant::fromValue(
                    Shared::ClientId(
                        p_presence.capabilityNode(),
                        p_presence.capabilityVer().toBase64(),
                        p_presence.capabilityHash())
                    )
                }
            });
        } break;
        case QXmppPresence::Unavailable:
            emit removePresence(jid, resource);
            break;
        case QXmppPresence::Subscribe:
            qDebug("xmpp presence \"subscribe\" received, do not yet know what to do, skipping");
            break;
        case QXmppPresence::Subscribed:
            qDebug("xmpp presence \"subscribed\" received, do not yet know what to do, skipping");
            break;
        case QXmppPresence::Unsubscribe:
            qDebug("xmpp presence \"unsubscribe\" received, do not yet know what to do, skipping");
            break;
        case QXmppPresence::Unsubscribed:
            qDebug("xmpp presence \"unsubscribed\" received, do not yet know what to do, skipping");
            break;
        case QXmppPresence::Probe:
            qDebug("xmpp presence \"probe\" received, do not yet know what to do, skipping");
            break;
    }
}

void Core::Account::onMamMessageReceived(const QString& queryId, const QXmppMessage& msg) {
    if (msg.id().size() > 0 && (msg.body().size() > 0 || msg.outOfBandUrl().size() > 0)) {
        std::map<QString, QString>::const_iterator itr = archiveQueries.find(queryId);
        if (itr != archiveQueries.end()) {
            QString jid = itr->second;
            RosterItem* item = rh->getRosterItem(jid);
            
            Shared::Message sMsg(static_cast<Shared::Message::Type>(msg.type()));
            mh->initializeMessage(sMsg, msg, false, true, true);
            sMsg.setState(Shared::Message::State::sent);
            
            QString oId = msg.replaceId();
            if (oId.size() > 0)
                item->correctMessageInArchive(oId, sMsg);
            else
                item->addMessageToArchive(sMsg);
        }
    }
}

void Core::Account::requestArchive(const QString& jid, int count, const QString& before) {
    qDebug() << "An archive request for " << jid << ", before " << before;
    RosterItem* item = rh->getRosterItem(jid);
    
    if (item == nullptr) {
        qDebug() << "An attempt to request archive for" << jid << "in account" << name << ", but the contact with such id wasn't found, skipping";
        emit responseArchive(jid, std::list<Shared::Message>(), true);
        return;
    }
    
    if (state != Shared::ConnectionState::connected) {
        qDebug() << "An attempt to request archive for" << jid << "in account" << name << ", but the account is not online, skipping";
        emit responseArchive(jid, std::list<Shared::Message>(), false);
        return;
    }
    
#ifdef WITH_OMEMO
    if (!item->isMuc()) {
        Contact* contact = static_cast<Contact*>(item);
        if (contact->omemoBundles == Shared::Possible::unknown)
            oh->requestBundles(jid);
    }
#endif
    item->requestHistory(count, before);
}

void Core::Account::onContactNeedHistory(const QString& before, const QString& after, const QDateTime& at) {
    RosterItem* contact = static_cast<RosterItem*>(sender());

    QString to;
    QString with;
    QXmppResultSetQuery query;
    QDateTime start;
    query.setMax(100);
    
    if (contact->getArchiveState() == RosterItem::empty) {
        query.setBefore(before);
        qDebug() << "Requesting remote history from empty for" << contact->jid;
    } else {
        if (before.size() > 0) {
            query.setBefore(before);
        }
        if (after.size() > 0) {     //there is some strange behavior of ejabberd server returning empty result set
            if (at.isValid()) {     //there can be some useful information about it here https://github.com/processone/ejabberd/issues/2924
                start = at;
            } else {
                query.setAfter(after);
            }
        }
        if (before.size() == 0 && after.size() == 0) {
            // https://xmpp.org/extensions/xep-0313.html#sect-idm46556759682304
            // To request the page at the end of the archive
            // (i.e. the most recent messages), include just an
            // empty <before/> element in the RSM part of the query.
            // As defined by RSM, this will return the last page of the archive.
            query.setBefore("");
        }
        qDebug() << "Remote query for" << contact->jid << "from" << after << ", to" << before;
    }
    
    if (contact->isMuc()) {
        to = contact->jid;
    } else {
        with = contact->jid;
    }
    
    QString q = am->retrieveArchivedMessages(to, "", with, start, QDateTime(), query);
    archiveQueries.insert(std::make_pair(q, contact->jid));
}

void Core::Account::onMamResultsReceived(const QString& queryId, const QXmppResultSetReply& resultSetReply, bool complete) {
    std::map<QString, QString>::const_iterator itr = archiveQueries.find(queryId);
    if (itr != archiveQueries.end()) {
        QString jid = itr->second;
        archiveQueries.erase(itr);
        
        RosterItem* ri = rh->getRosterItem(jid);
        
        if (ri != nullptr) {
            qDebug() << "Flushing messages for" << jid << ", complete:" << complete;
            ri->flushMessagesToArchive(complete, resultSetReply.first(), resultSetReply.last());
        }
    }
}

void Core::Account::onMamLog(QXmppLogger::MessageType type, const QString& msg) {
    SHARED_UNUSED(type);
    qDebug() << "MAM MESSAGE LOG::";
    qDebug() << msg;
}

void Core::Account::onClientError(QXmppClient::Error err) {
    qDebug() << "Error";
    QString errorText;
    QString errorType;
    lastError = Error::other;
    switch (err) {
        case QXmppClient::SocketError:
            errorText = client.socketErrorString();
            errorType = "Client socket error";
            break;
        case QXmppClient::XmppStreamError: {
            QXmppStanza::Error::Condition cnd = client.xmppStreamError();
            
            switch (cnd) {
                case QXmppStanza::Error::BadRequest:
                    errorText = "Bad request";
                    break;
                case QXmppStanza::Error::Conflict:
                    errorText = "Conflict";
                    break;
                case QXmppStanza::Error::FeatureNotImplemented:
                    errorText = "Feature is not implemented";
                    break;
                case QXmppStanza::Error::Forbidden:
                    errorText = "Forbidden";
                    break;
                case QXmppStanza::Error::Gone:
                    errorText = "Gone";
                    break;
                case QXmppStanza::Error::InternalServerError:
                    errorText = "Internal server error";
                    break;
                case QXmppStanza::Error::ItemNotFound:
                    errorText = "Item was not found";
                    break;
                case QXmppStanza::Error::JidMalformed:
                    errorText = "Malformed JID";
                    break;
                case QXmppStanza::Error::NotAcceptable:
                    errorText = "Not acceptable";
                    break;
                case QXmppStanza::Error::NotAllowed:
                    errorText = "Not allowed";
                    break;
                case QXmppStanza::Error::NotAuthorized:
                    errorText = "Authentication error";
                    lastError = Error::authentication;
                    break;
#if (QXMPP_VERSION) < QT_VERSION_CHECK(1, 3, 0)
                case QXmppStanza::Error::PaymentRequired:
                    errorText = "Payment is required";
                    break;
#endif
                case QXmppStanza::Error::RecipientUnavailable:
                    errorText = "Recipient is unavailable";
                    break;
                case QXmppStanza::Error::Redirect:
                    errorText = "Redirected";
                    break;
                case QXmppStanza::Error::RegistrationRequired:
                    errorText = "Registration is required";
                    break;
                case QXmppStanza::Error::RemoteServerNotFound:
                    errorText = "Remote server was not found";
                    break;
                case QXmppStanza::Error::RemoteServerTimeout:
                    errorText = "Remote server timeout";
                    break;
                case QXmppStanza::Error::ResourceConstraint:
                    errorText = "Resource constraint";
                    break;
                case QXmppStanza::Error::ServiceUnavailable:
                    errorText = "Redirected";
                    break;
                case QXmppStanza::Error::SubscriptionRequired:
                    errorText = "Subscription is required";
                    break;
                case QXmppStanza::Error::UndefinedCondition:
                    errorText = "Undefined condition";
                    reconnectScheduled = true;
                    reconnectTimer->start(500);     //let's reconnect here just for now, it seems to be something broken in QXMPP
                    break;
                case QXmppStanza::Error::UnexpectedRequest:
                    errorText = "Unexpected request";
                    break;
#if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 3, 0)
                case QXmppStanza::Error::PolicyViolation:
                    errorText = "Policy violation";
                    break;
#endif
                default:
                    errorText = "Unknown Error";
                    break;
            }
         
            errorType = "Client stream error";
        }
            
            break;
        case QXmppClient::KeepAliveError:
            errorText = "Client keep alive error";
            break;
        case QXmppClient::NoError:
            break;                      //not exactly sure what to do here
    }
    
    qDebug() << errorType << errorText;
    emit error(errorText);
}

void Core::Account::subscribeToContact(const QString& jid, const QString& reason) {
    if (state == Shared::ConnectionState::connected)
        rm->subscribe(jid, reason);
    else
        qDebug() << "An attempt to subscribe account " << name << " to contact " << jid << " but the account is not in the connected state, skipping";
}

void Core::Account::unsubscribeFromContact(const QString& jid, const QString& reason) {
    if (state == Shared::ConnectionState::connected)
        rm->unsubscribe(jid, reason);
    else
        qDebug() << "An attempt to unsubscribe account " << name << " from contact " << jid << " but the account is not in the connected state, skipping";
}

void Core::Account::removeContactRequest(const QString& jid) {
    rh->removeContactRequest(jid);}

void Core::Account::addContactRequest(const QString& jid, const QString& name, const QSet<QString>& groups) {
    rh->addContactRequest(jid, name, groups);}

void Core::Account::setRoomAutoJoin(const QString& jid, bool joined) {
    Conference* conf = rh->getConference(jid);
    if (conf == 0) {
        qDebug() << "An attempt to set auto join to the non existing room" << jid << "of the account" << getName() << ", skipping";
        return;
    }
    
    conf->setAutoJoin(joined);
}

void Core::Account::setRoomJoined(const QString& jid, bool joined) {
    Conference* conf = rh->getConference(jid);
    if (conf == 0) {
        qDebug() << "An attempt to set joined to the non existing room" << jid << "of the account" << getName() << ", skipping";
        return;
    }
    
    conf->setJoined(joined);
}

void Core::Account::setContactEncryption(const QString& jid, Shared::EncryptionProtocol value) {
    Contact* cnt = rh->getContact(jid);
    if (cnt == nullptr) {
        qDebug() << "An attempt to set encryption to the non-existing contact" << jid << "of the account" << getName() << ", skipping";
        return;
    }

    cnt->setEncryption(value);
}


void Core::Account::discoverInfo(const QString& address, const QString& node) {
    if (state == Shared::ConnectionState::connected) {
        dm->requestInfo(address, node);
    } else {
        qDebug() << "An attempt to send a discover info by account" << name <<
                    "sending request to" << address << "about node" << node <<
                    "but the account is not in the connected state, skipping";
    }
}

void Core::Account::setPepSupport(Shared::Support support) {
    if (support != pepSupport) {
        pepSupport = support;
        emit pepSupportChanged(pepSupport);
    }
}

void Core::Account::handleDisconnection() {
    setPepSupport(Shared::Support::unknown);
    delay->disconnected();
#if (QXMPP_VERSION) < QT_VERSION_CHECK(1, 5, 0)
    cm->setCarbonsEnabled(false);
#endif
    rh->handleOffline();
    archiveQueries.clear();
}

void Core::Account::onContactHistoryResponse(const std::list<Shared::Message>& list, bool last) {
    RosterItem* contact = static_cast<RosterItem*>(sender());
    
    qDebug() << "Collected history for contact " << contact->jid << list.size() << "elements";
    if (last)
        qDebug() << "The response contains the first accounted message";

    emit responseArchive(contact->jid, list, last);
}

bool Core::Account::getActive() const {
    return active;}

void Core::Account::setActive(bool p_active) {
    if (active != p_active) {
        active = p_active;

        emit changed({{"active", active}});
    }
}

QString Core::Account::getResource() const {
    return config.resource();}

void Core::Account::setResource(const QString& p_resource) {
    config.setResource(p_resource);}

QString Core::Account::getBareJid() const {
    return getLogin() + "@" + getServer();}

QString Core::Account::getFullJid() const {
    return getBareJid() + "/" + getResource();}

QString Core::Account::getName() const {
    return name;}

QString Core::Account::getLogin() const {
    return config.user();}

QString Core::Account::getPassword() const {
    return config.password();}

QString Core::Account::getServer() const {
    return config.domain();}

Shared::AccountPassword Core::Account::getPasswordType() const {
    return passwordType;}

void Core::Account::setPasswordType(Shared::AccountPassword pt) {
    passwordType = pt; }

void Core::Account::setLogin(const QString& p_login) {
    config.setUser(p_login);
    delay->setOwnJid(getBareJid());
}

void Core::Account::setName(const QString& p_name) {
    name = p_name;}

void Core::Account::setPassword(const QString& p_password) {
    config.setPassword(p_password);
    notReadyPassword = false;
}

void Core::Account::setServer(const QString& p_server) {
    config.setDomain(p_server);
    delay->setOwnJid(getBareJid());
}

void Core::Account::sendMessage(const Shared::Message& data) {
    mh->sendMessage(data);}

void Core::Account::requestChangeMessage(const QString& jid, const QString& messageId, const QMap<QString, QVariant>& data){
    mh->requestChangeMessage(jid, messageId, data);}

void Core::Account::resendMessage(const QString& jid, const QString& id) {
    mh->resendMessage(jid, id);}

void Core::Account::replaceMessage(const QString& originalId, const Shared::Message& data) {
    mh->sendMessage(data, false, originalId);}

void Core::Account::requestInfo(const QString& jid) {
    //TODO switch case of what kind of entity this info request is about
    //right now it could be only about myself or some contact
    delay->getInfo(jid);
    //vh->requestVCard(jid);
}

void Core::Account::updateInfo(const Shared::Info& info) {
    //TODO switch case of what kind of entity this info update is about
    //right now it could be only about myself
    vh->uploadVCard(info.getVCardRef());
    const std::list<Shared::KeyInfo>& keys = info.getActiveKeysRef();
    for (const Shared::KeyInfo& info : keys) {
        qDebug() << "An attempt to save key: ";
        qDebug() << "id:" << info.id;
        qDebug() << "label:" << info.label;
        qDebug() << "current device:" << info.currentDevice;
        qDebug() << "... but it's not implemented yet, ignoring";
    }
}

QString Core::Account::getAvatarPath() const {
    return vh->getAvatarPath();}

void Core::Account::removeRoomRequest(const QString& jid){
    rh->removeRoomRequest(jid);}

void Core::Account::addRoomRequest(const QString& jid, const QString& nick, const QString& password, bool autoJoin) {
    rh->addRoomRequest(jid, nick, password, autoJoin);}

void Core::Account::addContactToGroupRequest(const QString& jid, const QString& groupName) {
    rh->addContactToGroupRequest(jid, groupName);}

void Core::Account::removeContactFromGroupRequest(const QString& jid, const QString& groupName) {
    rh->removeContactFromGroupRequest(jid, groupName);}

void Core::Account::renameContactRequest(const QString& jid, const QString& newName) {
    Contact* cnt = rh->getContact(jid);
    if (cnt == 0)
        qDebug() << "An attempt to rename non existing contact" << jid << "of account" << name << ", skipping";
    else
        rm->renameItem(jid, newName);
}

void Core::Account::invalidatePassword() {
    notReadyPassword = true;}

Core::Account::Error Core::Account::getLastError() const {
    return lastError;}