/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */

/*
 *  Copyright (C) 2003 Takuro Ashie
 *  Copyright (C) 2003 Hiroyuki Ikezoe
 *
 *  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, 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 <gtk/gtk.h>
#include <glib/gi18n.h>
#include "kz-actions-download.h"
#include "kz-downloader-group.h"
#include "gtk-utils.h"

static void act_download_do (const gchar *uri,
			     const gchar* filename,
			     gboolean content);

gchar *
kz_actions_download_open_save_dialog (GtkWindow *window, 
    				      const gchar *uri,
				      gboolean content)
{
	GtkWidget *file_dialog;
	const gchar *basename = NULL;
	gchar *selected_filename = NULL;
	gint result;

	if (!uri) return NULL;

	basename = g_path_get_basename(uri);

	file_dialog = gtk_file_chooser_dialog_new (_("Save file"),
						   window, 
						   GTK_FILE_CHOOSER_ACTION_SAVE,
						   GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
						   GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
						   NULL);

	/* set default filename created from uri */
	gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(file_dialog), basename);

	/* Display that dialog */
	result = gtk_dialog_run(GTK_DIALOG(file_dialog));

	switch (result)
	{
	 case GTK_RESPONSE_ACCEPT:
		selected_filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(file_dialog));
		if (g_file_test(selected_filename, G_FILE_TEST_EXISTS))
		{
			gboolean ret;
			ret = gtkutil_confirm_file_replace(GTK_WINDOW(file_dialog),
							   selected_filename);
			if (!ret)
				break;
		}
		/* FIXME! it's the hacky way! */
		if (content)
		{
			gtk_widget_destroy(file_dialog);
			return selected_filename;
		}

		act_download_do(uri, selected_filename, content);
		break;
	 default:
		break;
	}
	gtk_widget_destroy(file_dialog);

	if (selected_filename)
		g_free(selected_filename);

	return NULL;
}



static void
act_download_do (const gchar *uri, const gchar* filename, gboolean content)
{	
	KzDownloaderGroup *dlgrp;

	dlgrp = kz_downloader_group_get_instance();
	kz_downloader_group_add_item_with_filename(dlgrp, uri, filename);
	g_warning("%s", filename);
	g_object_unref(dlgrp);
}
