/*
 * Copyright (C) 2005 Red Hat, Inc.
 * Copyright (C) 2006 Mark McLoughlin
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <config.h>

#include "menu-monitor-backend.h"

#ifdef HAVE_GNOMEVFS
#include <libgnomevfs/gnome-vfs.h>
#endif

#ifdef HAVE_GNOMEVFS

static gboolean initialized = FALSE;

static void
gvfs_event_callback (GnomeVFSMonitorHandle *handle,
		     const gchar *monitor_uri,
		     const gchar *info_uri,
		     GnomeVFSMonitorEventType event_type,
		     gpointer user_data)
{
    MenuMonitorEventInfo *event_info;
    MenuMonitorEvent	  event;
    char *                path;

    if (event_type == GNOME_VFS_MONITOR_CHANGED)
    {
	event = MENU_MONITOR_EVENT_CHANGED;
    } else if (event_type == GNOME_VFS_MONITOR_DELETED)
    {
	event = MENU_MONITOR_EVENT_DELETED;
    } else if (event_type == GNOME_VFS_MONITOR_CREATED)
    {
	event = MENU_MONITOR_EVENT_CREATED;
    } else {
	return;
    }

    path = gnome_vfs_get_local_path_from_uri (info_uri);

    event_info = g_new0 (MenuMonitorEventInfo, 1);

    event_info->path    = g_strdup (path);
    event_info->event   = event;
    event_info->monitor = monitor;

    menu_monitor_queue_event (event_info);
}
#endif

void
menu_monitor_backend_register_monitor (MenuMonitor *monitor)
{
#ifdef HAVE_GNOMEVFS
    GnomeVFSMonitorHandle *handle;
    GnomeVFSResult         result;
    GnomeVFSMonitorType    mtype;
    GnomeVFSFileInfo      *info;
    char                  *text_uri;

    if (initialized || !gnome_vfs_init ()) {
	initialized = TRUE;
	return;
    }
    initialized = TRUE;

    if (menu_monitor_menu_monitor_get_is_directory (monitor))
	mtype = GNOME_VFS_MONITOR_DIRECTORY;
    } else {
	mtype = GNOME_VFS_MONITOR_FILE;
    }

    text_uri = gnome_vfs_make_uri_from_input (menu_monitor_get_path (monitor));
    // setup monitor
    result = gnome_vfs_monitor_add (&handle,
				    text_uri,
				    mtype,
				    gvfs_event_callback,
				    NULL);

    menu_monitor_set_backend_data (monitor, handle);
#endif
}

void
menu_monitor_backend_unregister_monitor (MenuMonitor *monitor)
{
#ifdef HAVE_GNOMEVFS
    GnomeVFSMonitorHandle *handle;

    if (!initialized)
	return;

    handle = menu_monitor_get_backend_data (monitor);
    gnome_vfs_monitor_cancel (handle);
#endif
}

