/*
 * Mail Notification
 * Copyright (C) 2003-2008 Jean-Yves Lefort <jylefort@brutele.be>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

%headertop{
#include "mn-vfs-message.h"
%}

%{
#include <stdlib.h>
#include <glib/gi18n.h>
#include "mn-util.h"
#include "mn-sylpheed-mailbox-backend-private.h"
#include "mn-message-private.h"
%}

class MN:Sylpheed:Message from MN:VFS:Message
{
  override (MN:Message) void
    builtin_mark_as_read (MNMessage *message, MNMessageActionRequest *request)
  {
    mn_message_perform_action_in_thread(request, self_builtin_mark_as_read_cb, NULL);
  }

  private GError *
    builtin_mark_as_read_cb (MNMessage *message, gpointer data)
  {
    MNVFSMessage *vmessage = MN_VFS_MESSAGE(message);
    char *filename;
    guint32 num;
    guint32 flags;
    GError *tmp_err = NULL;
    GHashTable *marks;
    GError *err = NULL;

    filename = gnome_vfs_uri_extract_short_name(vmessage->vfs_uri);
    g_assert(mn_str_isnumeric(filename));
    num = atoi(filename);
    g_free(filename);

    /*
     * We hold the mailbox lock to prevent this:
     *
     *	  thread A: read mark file
     *	  thread B: read mark file
     *    thread A: write new mark file
     *    thread B: write new mark file, A's modifications are overwritten
     */
    mn_vfs_mailbox_lock(MN_VFS_MAILBOX(message->mailbox));

    marks = mn_sylpheed_mailbox_backend_read_marks(MN_VFS_MAILBOX(message->mailbox)->vfs_uri, &tmp_err);
    if (! marks)
      {
	g_set_error(&err, 0, 0, _("Unable to read %s: %s."), SYLPHEED_MARK_FILE, tmp_err->message);
	g_error_free(tmp_err);
	goto end;
      }

    flags = GPOINTER_TO_UINT(g_hash_table_lookup(marks, GUINT_TO_POINTER(num)));
    flags &= ~(SYLPHEED_MSG_NEW | SYLPHEED_MSG_UNREAD);
    g_hash_table_insert(marks, GUINT_TO_POINTER(num), GUINT_TO_POINTER(flags));

    mn_sylpheed_mailbox_backend_write_marks(MN_VFS_MAILBOX(message->mailbox)->vfs_uri, marks, &err);
    g_hash_table_destroy(marks);

  end:
    mn_vfs_mailbox_unlock(MN_VFS_MAILBOX(message->mailbox));

    return err;
  }
}
