/* ====================================================================
 * FTD4Linux Software License, Version 1.0
 *
 * Copyright (c) 2000-2004 The FTD4Linux Development Team.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        FTD4Linux Development Team (http://www.ftd4linux.2y.net/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "FTD" and "FTD4Linux" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact alguno@ftd4linux.2y.net.
 *
 * 5. Products derived from this software may not be called "FTD4Linux",
 *    nor may "FTD4Linux" appear in their name, without prior written
 *    permission of the FTD4Linux Development Team.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE FTD4LINUX DEVELOPMENT TEAM OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <dbus/dbus-glib.h>
#include <stdio.h>
#include <stdlib.h>
#include "ftd4linux.h"

static OpenFTDDBusObject *obj = NULL;
static DBusGProxy *bus_proxy = NULL;

typedef struct OpenFTDDBusObjectClass OpenFTDDBusObjectClass;

GType openftd_dbus_object_get_type (void);

struct OpenFTDDBusObject
{
    GObject parent;

    char *frontend_name;
    gboolean is_gui;
};

struct OpenFTDDBusObjectClass
{
  GObjectClass parent;
};

enum
{
  BRING_TO_FRONT_SIGNAL,
  OPEN_POSTING_SIGNAL,
  LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

#define OPENFTD_DBUS_TYPE_OBJECT              (openftd_dbus_object_get_type ())
#define OPENFTD_DBUS_OBJECT(object)           (G_TYPE_CHECK_INSTANCE_CAST ((object), OPENFTD_DBUS_TYPE_OBJECT, OpenFTDDBusObject))
#define OPENFTD_DBUS_OBJECT_CLASS(klass)      (G_TYPE_CHECK_CLASS_CAST ((klass), OPENFTD_DBUS_TYPE_OBJECT, OpenFTDDBusObjectClass))
#define OPENFTD_DBUS_IS_OBJECT(object)        (G_TYPE_CHECK_INSTANCE_TYPE ((object), OPENFTD_DBUS_TYPE_OBJECT))
#define OPENFTD_DBUS_IS_OBJECT_CLASS(klass)   (G_TYPE_CHECK_CLASS_TYPE ((klass), OPENFTD_DBUS_TYPE_OBJECT))
#define OPENFTD_DBUS_OBJECT_GET_CLASS(obj)    (G_TYPE_INSTANCE_GET_CLASS ((obj), OPENFTD_DBUS_TYPE_OBJECT, OpenFTDDBusObjectClass))

G_DEFINE_TYPE(OpenFTDDBusObject, openftd_dbus_object, G_TYPE_OBJECT)

gboolean openftd_dbus_is_gui(OpenFTDDBusObject *obj);
gboolean openftd_dbus_bring_to_front(OpenFTDDBusObject *obj);
gboolean openftd_dbus_open_posting(OpenFTDDBusObject *obj, int postID);

#include "openftd-dbus-glue.h"

static void
openftd_dbus_object_init (OpenFTDDBusObject *obj)
{
}

static void
openftd_dbus_object_class_init (OpenFTDDBusObjectClass *klass)
{
    signals[BRING_TO_FRONT_SIGNAL] = g_signal_new  ("bring_to_front",
                                                    G_OBJECT_CLASS_TYPE (klass),
                                                    G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
                                                    0,
                                                    NULL, NULL,
                                                    g_cclosure_marshal_VOID__VOID,
                                                    G_TYPE_NONE, 0);

    signals[OPEN_POSTING_SIGNAL] = g_signal_new    ("open_posting",
                                                    G_OBJECT_CLASS_TYPE (klass),
                                                    G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
                                                    0,
                                                    NULL, NULL,
                                                    g_cclosure_marshal_VOID__INT,
                                                    G_TYPE_NONE, 1, G_TYPE_INT);
}

gboolean
openftd_dbus_is_gui(OpenFTDDBusObject *obj)
{
    return obj->is_gui;
}

gboolean
openftd_dbus_bring_to_front(OpenFTDDBusObject *obj)
{
    g_signal_emit (obj, signals[BRING_TO_FRONT_SIGNAL], 0);

    return TRUE;
}

gboolean
openftd_dbus_open_posting(OpenFTDDBusObject *obj, int postID)
{
    g_signal_emit (obj, signals[OPEN_POSTING_SIGNAL], 0, postID);

    return TRUE;
}

static gboolean
ftd_dbus_test_is_already_active(DBusGConnection *connection)
{
    DBusGProxy *proxy = NULL;

    /* Create a proxy object for the "bus driver" (name "org.freedesktop.DBus") */
    proxy = dbus_g_proxy_new_for_name (connection,
                                       "org.OpenFTD.OpenFTD",
                                       "/org/OpenFTD/OpenFTD/object",
                                       "org.OpenFTD.OpenFTD");

    g_assert(proxy);

    if (dbus_g_proxy_call (proxy, "bringToFront", NULL, G_TYPE_INVALID, G_TYPE_INVALID)) {
        // Aanroep geslaagd, oftewel er is een ander FTD4Linux proces reeds actief
        g_object_unref (proxy);
        return TRUE;
    } else {
        g_object_unref (proxy);
        return FALSE;
    }
}

gboolean
ftd_dbus_initialize(gboolean is_gui, const char *frontend_name, gboolean *is_already_active, char **errmsg)
{
    DBusGConnection *bus;
    GError *error = NULL;
    guint request_name_result;

    g_type_init ();

    if (is_already_active) {
        *is_already_active = FALSE;
    }

    bus = dbus_g_bus_get (DBUS_BUS_SESSION, &error);
    if (!bus) {
        if (errmsg) {
            *errmsg = g_strdup_printf("Maken van verbinding met DBus mislukt:\n%s\n", error->message);
        }
        g_error_free(error);

        return FALSE;
    }

    if (ftd_dbus_test_is_already_active(bus)) {
        // Hey, er draait reeds een FTD4Linux proces.
        // We kunnen dit proces dus gaan afsluiten
        if (is_already_active) {
            *is_already_active = TRUE;
        }

        return FALSE;
    }

    dbus_g_object_type_install_info (OPENFTD_DBUS_TYPE_OBJECT, &dbus_glib_openftd_dbus_object_info);

    bus_proxy = dbus_g_proxy_new_for_name (bus, "org.freedesktop.DBus",
                                                "/org/freedesktop/DBus",
                                                "org.freedesktop.DBus");

    if (!dbus_g_proxy_call (bus_proxy, "RequestName", &error,
                            G_TYPE_STRING, "org.OpenFTD.OpenFTD",
                            G_TYPE_UINT, 0,
                            G_TYPE_INVALID,
                            G_TYPE_UINT, &request_name_result,
                            G_TYPE_INVALID)) {
        if (errmsg) {
            *errmsg = g_strdup_printf("Registreren van DBus path org.OpenFTD.OpenFTD mislukt:\n%s\n", error->message);
        }
        g_error_free(error);
    }

    obj = g_object_new (OPENFTD_DBUS_TYPE_OBJECT, NULL);
    obj->is_gui = is_gui;
    obj->frontend_name = g_strdup(frontend_name);

    dbus_g_connection_register_g_object (bus, "/org/OpenFTD/OpenFTD/object", G_OBJECT (obj));

    return TRUE;
}

void
ftd_dbus_cleanup(void)
{
    if (bus_proxy) {
        g_object_unref(bus_proxy);
        bus_proxy = NULL;
    }

    if (obj) {
        g_free(obj->frontend_name);
        obj->frontend_name = NULL;
        g_object_unref(obj);
    }
}

OpenFTDDBusObject *
ftd_dbus_get_object(void)
{
    return obj;
}
