#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dbus/dbus-glib.h>
#include <dbus/dbus.h>
#include <unistd.h>

DBusConnection *connect_dbus()
{
    DBusError err;
    DBusConnection *connection;
    int ret;

    dbus_error_init(&err);
    /* Connect to Bus*/
    connection = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
    if(dbus_error_is_set(&err))
    {
        fprintf(stderr,"Connection Err : %s\n",err.message);
        dbus_error_free(&err);
        exit(1);
    }

    ret = dbus_bus_request_name(connection,"test.wei.source", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
    if(dbus_error_is_set(&err)) 
    {
        fprintf(stderr,"Name Err : %s\n",err.message);
        dbus_error_free(&err);
    }

    return connection;
}

void send_a_method_call(DBusConnection *connection, const char *method_name)
{
    DBusError err;
    DBusMessage *msg, *reply;
    dbus_bool_t *stat;

    dbus_error_init(&err);

    msg = dbus_message_new_method_call ("com.kylin.MaintainMode","/com/kylin/MaintainMode/Object","com.kylin.MaintainMode.interface", method_name);

    if(msg == NULL) 
    {
        g_printerr("Message NULL");
        exit(1);
    }

    reply = dbus_connection_send_with_reply_and_block(connection, msg, -1, &err);
    if(dbus_error_is_set(&err))
    {
        fprintf(stderr, "Method call failed: %s\n", err.message);
        dbus_error_free(&err);
        dbus_message_unref(msg);
        exit(1);
    }

    if (reply)
    {
        DBusMessageIter iter;
        dbus_message_iter_init(reply, &iter);
        dbus_bool_t value;
        dbus_message_iter_get_basic(&iter, &value);
        printf("Method returned: %s\n", value ? "true" : "false");
        dbus_message_unref(reply);

    }

    dbus_connection_flush(connection);
    dbus_message_unref(msg);

}

int main( int argc , char **argv)
{
    DBusConnection * connection;

    connection = connect_dbus();

    if(connection == NULL) 
    {
        return -1;
    }

    send_a_method_call(connection, "OpenMaintainMode");
    return 0;
}