#include "bluetoothobexagent.h"

BluetoothObexAgent::BluetoothObexAgent(QObject *parent):ObexAgent(parent)
{
    if(daemonIsNotRunning())
    {
        qDebug() << Q_FUNC_INFO << __LINE__;
        QDBusConnection bus = QDBusConnection::sessionBus();
        if (!bus.registerService("com.ukui.bluetooth")) {  //注意命名规则-和_
                qDebug() << bus.lastError().message();
                exit(1);
        }
        // "QDBusConnection::ExportAllSlots"表示把类Hotel的所有Slot都导出为这个Object的method
        //qDebug() << Q_FUNC_INFO << bus.registerObject("/", "org.bluez.obex.Agent1", this, QDBusConnection::ExportAllContents);
        bus.registerObject("/", "org.bluez.obex.Agent1", this, QDBusConnection::ExportAllContents);
    }
    QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
                                         "/com/ukui/bluetooth",
                                         "com.ukui.bluetooth",
                                         "clearOldSession",
                                         this,
                                         SLOT(clearOldSession()));
    QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
                                         "/com/ukui/bluetooth",
                                         "com.ukui.bluetooth",
                                         "replyFileReceivingSignal",
                                         this,
                                         SLOT(replyFileReceivingSignalFunc(bool)));
    QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
                                         "/com/ukui/bluetooth",
                                         "com.ukui.bluetooth",
                                         "cancelFileReceivingSignal",
                                         this,
                                         SLOT(cancelFileReceivingSignalFunc()));
    QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
                                         "/com/ukui/bluetooth",
                                         "com.ukui.bluetooth",
                                         "continueRecieveFilesSignal",
                                         this,
                                         SLOT(continueRecieveFiles()));
}

void BluetoothObexAgent::authorizePush(BluezQt::ObexTransferPtr transfer, BluezQt::ObexSessionPtr session, const BluezQt::Request<QString> &request)
{
    qDebug() << Q_FUNC_INFO << transfer->status() << transfer->fileName() << transfer->name() <<transfer->objectPath().path() << transfer->transferred() << transfer->objectName();
    qDebug() << session->source() << session->destination();
    if (oldSession == session && transfer->status() != BluezQt::ObexTransfer::Error) {
        qDebug() << Q_FUNC_INFO << __LINE__;
        QDBusMessage fileReviceMore = QDBusMessage::createSignal("/com/ukui/bluetooth",
                                                    "com.ukui.bluetooth",
                                                    "fileReceiveMore");
        fileReviceMore << transfer->name() << transfer->size() << transfer->type();
        QDBusConnection::sessionBus().send(fileReviceMore);
        _Mtransfer = transfer;
        _Mrequest = &request;
        qDebug() << Q_FUNC_INFO << __LINE__;
        return;
    }
    qDebug() << Q_FUNC_INFO << __LINE__;
    if(transfer->status() == BluezQt::ObexTransfer::Queued ){//|| transfer->status() == BluezQt::ObexTransfer::Complete

        QDBusMessage statusChanged  = QDBusMessage::createSignal("/com/ukui/bluetooth",
                                                                        "com.ukui.bluetooth",
                                                                        "statusChanged");
        QMetaEnum metaEnum = QMetaEnum::fromType<BluezQt::ObexTransfer::Status>();
        statusChanged << metaEnum.valueToKey(transfer->status()) << session.data()->destination() << transfer.data()->objectPath().path();
        QDBusConnection::sessionBus().send(statusChanged);

        QDBusMessage fileReceivingSignal  = QDBusMessage::createSignal("/com/ukui/bluetooth",
                                                                        "com.ukui.bluetooth",
                                                                        "fileReceivingSignal");
        fileReceivingSignal << session->destination() << transfer->name() << transfer->type() << session->source() << transfer.data()->size();
        QDBusConnection::sessionBus().send(fileReceivingSignal);
        qDebug() << Q_FUNC_INFO << __LINE__;

        _Mtransfer = transfer;
        _Mrequest = &request;
        _Msession = session;
    }
    qDebug() << Q_FUNC_INFO << transfer->status() << transfer->type() << transfer->fileName() << transfer->transferred();
}

QDBusObjectPath BluetoothObexAgent::objectPath() const
{
    qDebug() << Q_FUNC_INFO;
    return QDBusObjectPath(QStringLiteral("/org/bluez/obex/Agent1"));
}

void BluetoothObexAgent::cancel()
{
    qDebug() << Q_FUNC_INFO;

    statusChangedSlot(BluezQt::ObexTransfer::Error);

    QDBusMessage obexAgentCanceled  = QDBusMessage::createSignal("/com/ukui/bluetooth",
                                                                    "com.ukui.bluetooth",
                                                                    "obexAgentCanceled");

    QDBusConnection::sessionBus().send(obexAgentCanceled);
    oldSession = nullptr;
}

void BluetoothObexAgent::release()
{
    qDebug() << Q_FUNC_INFO;
}

int BluetoothObexAgent::daemonIsNotRunning()
{
    QDBusConnection conn = QDBusConnection::sessionBus();
    if (!conn.isConnected())
        return 0;

    QDBusReply<QString> reply = conn.interface()->call("GetNameOwner", "org.bluez.obex.Agent1");
    return reply.value() == "";
}

void BluetoothObexAgent::continueRecieveFiles() {
    qDebug() << Q_FUNC_INFO << __LINE__;
    connect(_Mtransfer.data(), &BluezQt::ObexTransfer::transferredChanged, this, &BluetoothObexAgent::transferredChangedSlot);
    connect(_Mtransfer.data(), &BluezQt::ObexTransfer::statusChanged, this, &BluetoothObexAgent::statusChangedSlot);
    _Mrequest->accept(_Mtransfer.data()->name());
}

void BluetoothObexAgent::receiveDisConnectSignal(QString address)
{
    qDebug() << Q_FUNC_INFO << address << __LINE__;

    QDBusMessage m = QDBusMessage::createMethodCall("org.ukui.bluetooth","/org/ukui/bluetooth","org.ukui.bluetooth","disConnectToDevice");
    m << address;
    qDebug() << Q_FUNC_INFO << m.arguments().at(0).value<QString>() <<__LINE__;
    // 发送Message
    QDBusMessage response = QDBusConnection::sessionBus().call(m);
}

void BluetoothObexAgent::replyFileReceivingSignalFunc(bool value)
{
    qDebug() << Q_FUNC_INFO << __LINE__;
    if (value) {
        qDebug() << Q_FUNC_INFO << __LINE__;
        _Mrequest->accept(_Mtransfer.data()->name());
        oldSession = _Msession;
        qDebug() << Q_FUNC_INFO << __LINE__;

        QDBusMessage initTransferPath  = QDBusMessage::createSignal("/com/ukui/bluetooth",
                                                                        "com.ukui.bluetooth",
                                                                        "initTransferPath");
        initTransferPath << _Mtransfer.data()->objectPath().path() << false;

        QDBusConnection::sessionBus().send(initTransferPath);

        connect(_Mtransfer.data(), &BluezQt::ObexTransfer::transferredChanged, this, &BluetoothObexAgent::transferredChangedSlot);
        connect(_Mtransfer.data(), &BluezQt::ObexTransfer::statusChanged, this, &BluetoothObexAgent::statusChangedSlot);
    } else {

        statusChangedSlot(BluezQt::ObexTransfer::Error);

        _Mrequest->reject();
        clearOldSession();
    }
}

void BluetoothObexAgent::cancelFileReceivingSignalFunc() {
    _Mtransfer.data()->cancel();
    qDebug() << Q_FUNC_INFO << __LINE__;
}

void BluetoothObexAgent::transferredChangedSlot(quint64 size) {
    QDBusMessage transferredChanged  = QDBusMessage::createSignal("/com/ukui/bluetooth",
                                                                    "com.ukui.bluetooth",
                                                                    "transferredChanged");
    transferredChanged << QVariant::fromValue(size) << _Mtransfer.data()->objectPath().path();

    QDBusConnection::sessionBus().send(transferredChanged);
}

void BluetoothObexAgent::statusChangedSlot(BluezQt::ObexTransfer::Status status) {
    QDBusMessage statusChanged  = QDBusMessage::createSignal("/com/ukui/bluetooth",
                                                                    "com.ukui.bluetooth",
                                                                    "statusChanged");
    QMetaEnum metaEnum = QMetaEnum::fromType<BluezQt::ObexTransfer::Status>();
    statusChanged << metaEnum.valueToKey(status) << _Msession.data()->destination() << _Mtransfer.data()->objectPath().path();
    QDBusConnection::sessionBus().send(statusChanged);
}

void BluetoothObexAgent::clearOldSession() {

    oldSession = nullptr;
}
