/*
   SPDX-FileCopyrightText: 2022-2026 Laurent Montel <montel@kde.org>

   SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "myaccountmanagedeviceconfigurewidget.h"

#include "connection.h"
#include "misc/searchwithdelaylineedit.h"
#include "model/deviceinfomodel.h"
#include "model/deviceinfoproxymodel.h"
#include "model/searchtreebasefilterproxymodel.h"
#include "rocketchataccount.h"
#include "ruqolawidgets_debug.h"
#include "sessions/sessionslistjob.h"
#include "sessions/sessionslogoutmejob.h"
#include <KLocalizedString>
#include <QLabel>
#include <QMenu>
#include <QTreeView>

using namespace Qt::Literals::StringLiterals;
MyAccountManageDeviceConfigureWidget::MyAccountManageDeviceConfigureWidget(RocketChatAccount *account, QWidget *parent)
    : SearchTreeBaseWidget(account, parent)
{
    mModel = new DeviceInfoModel(this);
    mModel->setObjectName(u"mModel"_s);
    mSearchLineEdit->setPlaceholderText(i18nc("@info:placeholder", "Search device…"));

    mProxyModelModel = new DeviceInfoProxyModel(mModel, this);
    mProxyModelModel->setObjectName(u"mProxyModelModel"_s);
    mTreeView->setModel(mProxyModelModel);
    hideColumns();
    connectModel();
}

MyAccountManageDeviceConfigureWidget::~MyAccountManageDeviceConfigureWidget() = default;

void MyAccountManageDeviceConfigureWidget::updateLabel()
{
    mLabelResultSearch->setText(mModel->total() == 0 ? i18n("No device found") : displayShowMessage());
}

QString MyAccountManageDeviceConfigureWidget::displayShowMessage() const
{
    QString displayMessageStr = i18np("%1 device (Total: %2)", "%1 devices (Total: %2)", mModel->rowCount(), mModel->total());
    if (!mModel->hasFullList()) {
        displayMessageStr += clickableStr();
    }
    return displayMessageStr;
}

void MyAccountManageDeviceConfigureWidget::slotLoadElements(int offset, int count, const QString &searchName)
{
    if (!mRocketChatAccount->offlineMode()) {
        auto job = new RocketChatRestApi::SessionsListJob(this);

        RocketChatRestApi::QueryParameters parameters;
        //    QMap<QString, RocketChatRestApi::QueryParameters::SortOrder> map;
        //    map.insert(u"name"_s, RocketChatRestApi::QueryParameters::SortOrder::Ascendant);
        //    parameters.setSorting(map);
        if (offset != -1) {
            parameters.setOffset(offset);
        }
        if (count != -1) {
            parameters.setCount(count);
        }
        if (!searchName.isEmpty()) {
            parameters.setFilter(searchName);
        }

        job->setQueryParameters(parameters);

        mRocketChatAccount->restApi()->initializeRestApiJob(job);
        if (offset != -1) {
            connect(job, &RocketChatRestApi::SessionsListJob::sessionsListDone, this, &MyAccountManageDeviceConfigureWidget::slotLoadMoreElementDone);
        } else {
            connect(job, &RocketChatRestApi::SessionsListJob::sessionsListDone, this, &MyAccountManageDeviceConfigureWidget::slotSearchDone);
        }
        if (!job->start()) {
            qCWarning(RUQOLAWIDGETS_LOG) << "Impossible to start SessionsListJob job";
        }
    }
}

void MyAccountManageDeviceConfigureWidget::slotDeviceRemoved(const QByteArray &emojiId)
{
    mModel->removeElement(emojiId);
}

void MyAccountManageDeviceConfigureWidget::slotCustomContextMenuRequested(const QPoint &pos)
{
    const QModelIndex index = mTreeView->indexAt(pos);
    if (index.isValid()) {
        QMenu menu(this);
        const QModelIndex newModelIndex = mProxyModelModel->mapToSource(index);
        menu.addAction(QIcon::fromTheme(u"list-remove"_s), i18nc("@action", "Disconnect"), this, [this, newModelIndex]() {
            const QModelIndex modelIndex = mModel->index(newModelIndex.row(), DeviceInfoModel::Identifier);
            slotDisconnectDevice(modelIndex);
        });
        menu.exec(mTreeView->viewport()->mapToGlobal(pos));
    }
}

void MyAccountManageDeviceConfigureWidget::slotDisconnectDevice(const QModelIndex &index)
{
    auto job = new RocketChatRestApi::SessionsLogoutMeJob(this);
    const QModelIndex modelIndex = mModel->index(index.row(), DeviceInfoModel::SessionId);
    const QByteArray sessionsId = modelIndex.data().toByteArray();
    job->setSessionId(sessionsId);
    mRocketChatAccount->restApi()->initializeRestApiJob(job);
    connect(job, &RocketChatRestApi::SessionsLogoutMeJob::logoutMeDone, this, [this, sessionsId]() {
        slotDeviceRemoved(sessionsId);
    });
    if (!job->start()) {
        qCWarning(RUQOLAWIDGETS_LOG) << "Impossible to start SessionsLogoutMeJob job";
    }
}

#include "moc_myaccountmanagedeviceconfigurewidget.cpp"
