#include <gtk/gtk.h>
#include <glib/gstdio.h>
#include <gio/gio.h>

static gboolean
window_delete_cb(GtkWidget *widget, GdkEvent *event, gpointer *data)
{
    gtk_main_quit();
    return FALSE;
}

static void
drive_changed_cb(GVolumeMonitor *gvm, GDrive *gd, gpointer *data)
{
    gchar *device;
    GList *link, *drives;

    device = g_drive_get_identifier(gd, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);
    g_message("change device: %s", device);

    link = drives = g_volume_monitor_get_connected_drives(gvm);
    if (drives == NULL)
        return;

    while (link != NULL)
    {
        gchar *drive;

        drive = g_drive_get_identifier(link->data, 
                                        G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);
        if (drive != NULL)
        {
            g_message("drive: %s", drive);
            g_free(drive);
        }
        g_object_unref(link->data);
        link = link->next;
    }
    g_list_free(drives);
}

static gboolean
file_chooser_idle(gpointer *data)
{
    GtkWidget *dialog;
    gint response;

    dialog = gtk_file_chooser_dialog_new("Open File", GTK_WINDOW(data),
        GTK_FILE_CHOOSER_ACTION_OPEN, "Cancel", GTK_RESPONSE_CANCEL,
        "Open", GTK_RESPONSE_ACCEPT, NULL);
    response = gtk_dialog_run(GTK_DIALOG(dialog));
    if (response == GTK_RESPONSE_ACCEPT)
    {
        gchar *filename;

        filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
        g_message("filename: %s", filename);
        g_free(filename);
    }
    gtk_widget_destroy(dialog);
    return FALSE;
}

int
main (int argc, char *argv[])
{
    GVolumeMonitor *gvm;
    GtkWidget *window;

    if (!g_thread_supported())
        g_thread_init(NULL);
    
    gtk_init (&argc, &argv);

    g_log_set_always_fatal(G_LOG_LEVEL_CRITICAL);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect(window, "delete-event", (GCallback)window_delete_cb, NULL);
    gtk_widget_show(window);
    g_idle_add((GSourceFunc)file_chooser_idle, window);

    // Enable events that alert us to media change events
    gvm = g_volume_monitor_get ();
    g_signal_connect(gvm, "drive-changed", (GCallback)drive_changed_cb, NULL);

    gtk_main ();
    return 0;
}
