#include "wiredlinkstate.h"

WiredLinkState::WiredLinkState(QObject *parent) : QObject(parent)
{
    initConnectionInfo();
}

bool WiredLinkState::getWiredState()
{
    return myWiredState;
}

int WiredLinkState::getWiredStateValue()
{
    return myWiredStateValue;
}

bool WiredLinkState::initConnectionInfo()
{
    int connectivityState = 0;
    myWiredState = false;
    QDBusConnection::systemBus().connect(QString("org.freedesktop.NetworkManager"),
                                         QString("/org/freedesktop/NetworkManager"),
                                         QString("org.freedesktop.NetworkManager"),
                                         QString("PropertiesChanged"), this, SLOT(onPropertiesChanged(QVariantMap) ) );

    QDBusInterface interface( "org.freedesktop.NetworkManager",
                              "/org/freedesktop/NetworkManager",
                              "org.freedesktop.DBus.Properties",
                              QDBusConnection::systemBus() );

    //获取已经连接了那些网络，及这些网络对应的网络类型(ethernet or wifi)
    QDBusMessage result = interface.call("Get", "org.freedesktop.NetworkManager", "ActiveConnections");
    QList<QVariant> outArgs = result.arguments();
    QVariant first = outArgs.at(0);
    QDBusVariant dbvFirst = first.value<QDBusVariant>();
    QVariant vFirst = dbvFirst.variant();
    QDBusArgument dbusArgs = vFirst.value<QDBusArgument>();

    QDBusObjectPath objPath;
    dbusArgs.beginArray();

    while (!dbusArgs.atEnd()) {
        dbusArgs >> objPath;
        QDBusInterface interfacePath( "org.freedesktop.NetworkManager",
                                  objPath.path(),
                                  "org.freedesktop.DBus.Properties",
                                  QDBusConnection::systemBus() );

        QDBusReply<QVariant> replyType = interfacePath.call("Get", "org.freedesktop.NetworkManager.Connection.Active", "Type");

        QDBusReply<QVariant> replyState = interfacePath.call("Get", "org.freedesktop.NetworkManager.Connection.Active", "State");

        if (replyType.value().toString().indexOf("ethernet") != -1 && replyState.value().toString() == "2") {
            QDBusReply<QVariant> replyConnectivity = interface.call("Get", "org.freedesktop.NetworkManager", "Connectivity");
            connectivityState = replyConnectivity.value().toInt();
            myWiredStateValue = connectivityState;

            wiredStateChange = true;
            myWiredState = true;
            emit wiredLinkChanged(true);
            return myWiredState;
        }
    }
    myWiredStateValue = 0;
    emit wiredLinkChanged(false);
    return myWiredState;
}

void WiredLinkState::onPropertiesChanged(QVariantMap)
{
    initConnectionInfo();
}
