/*
 *  Copyright (C) 2004 Mathias Andre <mathias@openbrookes.org>
 *
 *  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 2 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 */

#include <glib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libgnomevfs/gnome-vfs.h>

#include "nb_attachment.h"

#define _(text) gettext(text)

/* create and free object */
Attachment *
nb_attachment_new (gchar * uri, gchar * mime_type)
{
	Attachment * self = g_malloc (sizeof (Attachment));
	self->uri = uri;
	self->mime_type = mime_type;

	return self;
}

void
nb_attachment_free (Attachment * self)
{
	g_free (self->uri);
	g_free (self->mime_type);
	g_free (self);
}

/* read/write from/to xml doc */
Attachment *
nb_attachment_new_from_xml_doc (xmlDocPtr doc, xmlNodePtr cur)
{
	 xmlChar * uri = NULL;
	 xmlChar * mime_type = NULL;

	 cur = cur->xmlChildrenNode;

	 while ( cur != NULL )
	 {
		 /* get the uri */
		 if ( !xmlStrcmp (cur->name, (const xmlChar *) "uri") )
		 {
			 uri = xmlNodeListGetString (doc, cur->xmlChildrenNode, 1);
		 }

		 /* get the mime_type */
		 if ( !xmlStrcmp (cur->name, (const xmlChar *) "mime") )
		 {
			 mime_type = xmlNodeListGetString (doc, cur->xmlChildrenNode, 1);
		 }

		 cur = cur->next;
	 }

	 return  nb_attachment_new (uri, mime_type);
}

xmlNodePtr
nb_attachment_get_xml_pointer (Attachment * self, xmlNsPtr ns)
{
	xmlNodePtr cur;

	 /* create a new attachment node */
	cur = xmlNewNode (ns, "attachment");

	xmlNewTextChild (cur, ns, "uri", self->uri);
	xmlNewTextChild (cur, ns, "mime_type", self->mime_type);

	return cur;
}

/* check if the uri is still valid */
gboolean 
nb_attachment_check (Attachment * self)
{
	gchar * text = NULL;
	GnomeVFSURI * uri = gnome_vfs_uri_new (self->uri);

	if ( gnome_vfs_uri_exists (uri) )
		return TRUE;

	/*nb_ui_dialog_error (_("Can't open file %s\n"), 
			    gnome_vfs_uri_to_string (uri, GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD)); */

	text = g_strconcat ("The file", gnome_vfs_uri_to_string (uri, GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD), " doesn't exist. \n Remove the link to the attachment from the note?", NULL);

	if ( nb_ui_dialog_question (text, "Cannot open file") )
	{
		g_free (text);
		return FALSE;
	}
	
	g_free (text);
	return TRUE;
}
