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

/*
 *  Copyright (C) 2003 Hiroyuki Ikezoe
 *  Copyright (C) 2003 Takuro Ashie
 *
 *  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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */

#include <stdio.h>
#include <string.h>
#include <glib/gi18n.h>

#include "kz-io.h"
#include "kz-http.h"
#include "kz-file.h"
#include "kz-marshalers.h"

#define BUFFER_SIZE 1024

enum {
	IO_START_SIGNAL,
	IO_PROGRESS_SIGNAL,
	IO_COMPLETED_SIGNAL,
	IO_LAST_SIGNAL
};

enum {
	PROP_0,
	PROP_URI,
	PROP_MODE,
	PROP_LASTMODIFIED,
	PROP_FILESIZE
};

static void set_property    (GObject *object,
                             guint prop_id,
                             const GValue *value,
                             GParamSpec *pspec);
static void get_property    (GObject *object,
                             guint prop_id,
                             GValue *value,
                             GParamSpec *pspec);
static void dispose         (GObject *object);

static void     kz_io_set_mode        (KzIO *io, KzIOMode mode); /* read or write mode */
static void     kz_io_set_buffer_mode (KzIO *io);
static gboolean kz_io_is_buffer_mode  (KzIO *io);

/* virtual function  */
static GIOStatus real_read_from_io (KzIO *io, GIOChannel *iochannel);
static GIOStatus real_write_to_io  (KzIO *io, GIOChannel *iochannel);
static void      real_start        (KzIO *io);

static void      io_error          (KzIO *io);
static void      io_set_iochannel  (KzIO *io);
static void      io_to_buffer      (KzIO *io, gsize len, const gchar *buf);
static void      buffer_to_io      (KzIO *io, gsize len, const gchar *buf);

static gboolean  cb_io_in          (GIOChannel *iochannel,
				    GIOCondition condition,
				    gpointer data);
static gboolean  cb_io_out         (GIOChannel *iochannel,
				    GIOCondition condition,
				    gpointer data);

typedef struct _KzIOPrivate KzIOPrivate;
struct _KzIOPrivate 
{
	gchar *uri;

	KzIOMode mode;
	guint source_id;

	guint file_size;
	guint loaded_size;	
	guint last_modified;

	GString *buffer;

	gchar *localfile;        /* local file name */
	GIOChannel *localfileio; /* for local file */

	const gchar *write_buffer;

	gboolean cancel;
	gboolean buffer_mode;
	
	GError *error;
};

#define KZ_IO_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), KZ_TYPE_IO, KzIOPrivate))

GType
kz_io_mode_type_get_type (void)
{
	static GType etype = 0;
	if (etype == 0) {
		static const GEnumValue values[] = {
			{ KZ_IO_READ,  "KZ_IO_READ",  "READ" },
			{ KZ_IO_WRITE, "KZ_IO_WRITE", "WRITE" },
			{ 0, NULL, NULL }
		};
		etype = g_enum_register_static ("KzIOMode", values);
	}
	return etype;
}

static gint kz_io_signals[IO_LAST_SIGNAL] = {0};

static GQuark error_quark     = 0;

/* static GQuark redirect_quark  = 0; */
G_DEFINE_TYPE(KzIO, kz_io, G_TYPE_OBJECT)

static void
kz_io_class_init (KzIOClass *klass)
{
	GObjectClass *object_class;

	object_class = (GObjectClass *) klass;

	object_class->dispose      = dispose;
	object_class->set_property = set_property;
	object_class->get_property = get_property;
	
	klass->io_progress         = NULL;
	klass->io_completed        = NULL;
	
	klass->read_from_io   = real_read_from_io;
	klass->write_to_io    = real_write_to_io;
	klass->io_start       = real_start;
	klass->io_error       = io_error;
	klass->io_set_channel = io_set_iochannel;
	klass->io_to_buffer   = io_to_buffer;
	klass->buffer_to_io   = buffer_to_io;

	g_object_class_install_property(
		object_class,
		 PROP_URI,
		 g_param_spec_string(
			 "uri",
			 _("URI"),
			 _("The URI of Fetch file"),
			 NULL,
			 G_PARAM_READWRITE));

	g_object_class_install_property(
		object_class,
		PROP_MODE,
		g_param_spec_enum(
			"mode",
			_("I/O Mode"),
			_("Read or write mode"),
			KZ_TYPE_IO_MODE,
			KZ_IO_READ,
			G_PARAM_READWRITE));
	g_object_class_install_property(
		object_class,
		PROP_LASTMODIFIED,
		g_param_spec_uint(
			"last_modified",
			_("Last Modified"),
			_("The last modified time of the fetch file"),
			0,
			G_MAXUINT,
			0,
			G_PARAM_READWRITE));
	g_object_class_install_property(
		object_class,
		PROP_FILESIZE,
		g_param_spec_uint(
			"file_size",
			_("File size"),
			_("The size of the fetch file"),
			0,
			G_MAXUINT,
			0,
			G_PARAM_READWRITE));

	kz_io_signals[IO_PROGRESS_SIGNAL]
		= g_signal_new ("io_progress",
				G_TYPE_FROM_CLASS (klass),
				G_SIGNAL_RUN_LAST,
				G_STRUCT_OFFSET (KzIOClass, io_progress),
				NULL, NULL,
				_kz_marshal_VOID__UINT_STRING,
				G_TYPE_NONE, 2,
				G_TYPE_UINT, G_TYPE_STRING);
	kz_io_signals[IO_COMPLETED_SIGNAL]
		= g_signal_new ("io_completed",
				G_TYPE_FROM_CLASS (klass),
				G_SIGNAL_RUN_LAST,
				G_STRUCT_OFFSET (KzIOClass, io_completed),
				NULL, NULL,
				g_cclosure_marshal_VOID__POINTER,
				G_TYPE_NONE, 1,
				G_TYPE_POINTER);

	error_quark       = g_quark_from_string("KzIO::Error");
	g_type_class_add_private (object_class, sizeof(KzIOPrivate));
}


static void
kz_io_init (KzIO *io)
{
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (io);
	
	priv->uri         = NULL;

	priv->source_id   = 0;

	priv->file_size   = 0;
	priv->loaded_size = 0;

	priv->localfileio = NULL;
	priv->localfile   = NULL;

	priv->cancel      = FALSE;
	priv->buffer_mode = FALSE;
	
	priv->error       = NULL;

	io->iochannel     = NULL;
}


void
dispose (GObject *object)
{
	KzIO *io;
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (object);

	io = KZ_IO(object);

	if (io->iochannel)
	{
		g_io_channel_unref(io->iochannel);
		io->iochannel = NULL;
	}
	if (priv->localfileio)
		g_io_channel_unref(priv->localfileio);
	if (priv->localfile)
	{
		g_free(priv->localfile);
	}
	if (priv->uri)
		g_free(priv->uri);
	if (priv->buffer)
		g_string_free(priv->buffer, TRUE);
	if (priv->error)
		g_error_free(priv->error);

	if (priv->source_id)
		g_source_remove(priv->source_id);
	priv->source_id = 0;
	priv->uri       = NULL;
	priv->localfile = NULL;
	priv->buffer    = NULL;
	priv->error     = NULL;

	if (G_OBJECT_CLASS (kz_io_parent_class)->dispose)
		G_OBJECT_CLASS (kz_io_parent_class)->dispose(object);
}


static void
set_property (GObject *object,
              guint prop_id,
              const GValue *value,
              GParamSpec *pspec)
{
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (object);

	switch (prop_id)
	{
	case PROP_URI:
		g_free(priv->uri);
		priv->uri = g_value_dup_string(value);
		break;
	case PROP_MODE:
		priv->mode = g_value_get_enum(value);
		break;
	case PROP_LASTMODIFIED:
		priv->last_modified = g_value_get_uint(value);
		break;
	case PROP_FILESIZE:
		priv->file_size = g_value_get_uint(value);
		break;	
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
		break;
	}
}


static void
get_property (GObject *object,
              guint prop_id,
              GValue *value,
              GParamSpec *pspec)
{
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (object);

	switch (prop_id)
	{
	case PROP_URI:
		g_value_set_string(value, priv->uri);
		break;
	case PROP_MODE:
		g_value_set_enum(value, priv->mode);
		break;
	case PROP_LASTMODIFIED:
		g_value_set_uint(value, priv->last_modified);
		break;
	case PROP_FILESIZE:
		g_value_set_uint(value, priv->file_size);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
		break;
	}
}


KzIO *
kz_io_new (const gchar *uri)
{
	KzIO *io = NULL;

	if (!uri) return NULL;

	/* FIXME! I think this code is something wrong. */
	if (g_str_has_prefix(uri, "http://"))
	{
		io = KZ_IO(kz_http_new(uri));
	}
#ifdef USE_SSL
	else if (g_str_has_prefix(uri, "https://"))
	{
		io = KZ_IO(kz_http_new(uri));
	}
#endif
	else if (g_str_has_prefix(uri, "ftp://"))
	{
		/* io = KZ_IO(kz_ftp_new(uri)); */
	}
	else if (g_str_has_prefix(uri, "file://"))
	{
		io = KZ_IO(kz_file_new(uri + 7));
	}	    
	else
	{
		io = KZ_IO(kz_file_new(uri));
	}	    

	return io;
}


static void
io_error (KzIO *io)
{
	KzIOPrivate *priv;
	g_return_if_fail(KZ_IS_IO(io));

	priv = KZ_IO_GET_PRIVATE (io);
	priv->error = g_error_new(error_quark,
				  KZ_IO_ERROR,
				  _("Error"));
				      
	g_signal_emit(io,
		      kz_io_signals[IO_COMPLETED_SIGNAL],
		      0,
		      priv->error);
}


static void
io_to_buffer (KzIO *io, gsize len, const gchar *buf)
{
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (io);
	gsize bytes_written;
	
	if (kz_io_is_buffer_mode(io))
		g_string_append_len(priv->buffer, buf, len);
	else
	{
		g_io_channel_write_chars(priv->localfileio,
					 buf,
					 len,
					 &bytes_written,
					 NULL);
	}
	priv->loaded_size += len;

	g_signal_emit(io,
		      kz_io_signals[IO_PROGRESS_SIGNAL],
		      0,
		      len, buf);
}


static void
buffer_to_io (KzIO *io, gsize len, const gchar *buf)
{
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (io);
	GIOStatus iostatus;
	gssize count;
	gsize bytes_written;

	count = strlen(priv->write_buffer);

	iostatus = g_io_channel_write_chars(io->iochannel,
					    priv->write_buffer,
					    count,
					    &bytes_written,
					    NULL);
	g_signal_emit(io,
		      kz_io_signals[IO_PROGRESS_SIGNAL],
		      0,
		      len, buf);
}


#include <errno.h>
static gboolean
cb_io_in(GIOChannel *iochannel, GIOCondition condition,
	 gpointer data)
{
	KzIO *io;
	KzIOPrivate *priv;
	GIOStatus iostatus;
	
	g_return_val_if_fail(KZ_IS_IO(data), FALSE);
	io = KZ_IO(data);
	priv = KZ_IO_GET_PRIVATE (io);
	
	/* If kz_io_stop have been called, loading stops.  */
	if (priv->cancel)
	{
		io_error(io);
		return FALSE;
	}

	if (condition & G_IO_ERR)
	{
		g_warning("IO Condition: %d", condition);
		io_error(io);
		return FALSE;
	}

	iostatus = KZ_IO_GET_CLASS(io)->read_from_io(io, iochannel);

	switch (iostatus)
	{
	 case G_IO_STATUS_EOF:
		if(priv->localfile)
		{
			g_io_channel_flush(priv->localfileio, NULL);
		}
		g_signal_emit(io,
			      kz_io_signals[IO_COMPLETED_SIGNAL],
			      0, NULL);
		return FALSE;
	 case G_IO_STATUS_NORMAL:
		return TRUE;
	 case G_IO_STATUS_AGAIN :
		if(priv->localfile)
		{
			g_io_channel_flush(priv->localfileio, NULL);
			g_io_channel_unref(priv->localfileio);
			priv->localfileio = NULL;
		}

		kz_io_start(io);
		return FALSE;
	 default:
		io_error(io);
		return FALSE;
	}
}


static gboolean
cb_io_out(GIOChannel *iochannel, GIOCondition condition,
	  gpointer data)
{
	KzIO *io;
	KzIOPrivate *priv;
	GIOStatus iostatus;
	
	g_return_val_if_fail(KZ_IS_IO(data), FALSE);
	io = KZ_IO(data);
	priv = KZ_IO_GET_PRIVATE (io);
	
	/* If kz_io_stop have been called, writing stops.  */
	if (priv->cancel)
	{
		io_error(io);
		return FALSE;
	}

	if ((condition & G_IO_ERR) || (condition & G_IO_HUP))
	{
		g_warning("IO Condition: %d", condition);
		io_error(io);
		return FALSE;
	}
	iostatus = KZ_IO_GET_CLASS(io)->write_to_io(io, iochannel);

	switch (iostatus)
	{
	 case G_IO_STATUS_EOF:
		g_io_channel_flush(iochannel, NULL);		
		g_signal_emit(io,
			      kz_io_signals[IO_COMPLETED_SIGNAL],
			      0, NULL);
		return FALSE;
	 case G_IO_STATUS_NORMAL:
		return TRUE;
	 default:
		io_error(io);
		return FALSE;
	}
}


static GIOStatus
real_read_from_io (KzIO *io, GIOChannel *iochannel)
{
	/* this function is not called. */	
	return G_IO_STATUS_NORMAL;
}


static GIOStatus
real_write_to_io (KzIO *io, GIOChannel *iochannel)
{
	/* this function is not called */
	return G_IO_STATUS_NORMAL;
}


static void
real_start (KzIO *io)
{
	/* this function is not called. */
}


static void 
io_set_iochannel(KzIO *io)
{
	GIOStatus iostatus;
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (io);

	g_io_channel_set_buffered(io->iochannel, TRUE);

	if (kz_io_get_mode(io) == KZ_IO_READ)
	{
		iostatus = g_io_channel_set_flags(io->iochannel,
						  G_IO_FLAG_NONBLOCK,
						  NULL);
		if (iostatus != G_IO_STATUS_NORMAL)
			io_error(io);

		priv->source_id = g_io_add_watch(io->iochannel,
			       G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP,
			       cb_io_in, io);

		if  (kz_io_is_buffer_mode(io))
			priv->buffer = g_string_new(0);
		else
		{
			priv->localfileio = g_io_channel_new_file(priv->localfile, "w", NULL);
			if (priv->localfileio)
			{
				iostatus = g_io_channel_set_encoding(priv->localfileio,
								     NULL,
								     NULL);
				g_io_channel_set_buffered(priv->localfileio, TRUE);
			}
			else 
				io_error(io);
		}
	}
	else if (kz_io_get_mode(io) == KZ_IO_WRITE)
		cb_io_out(io->iochannel, G_IO_OUT, io);
}


static void
kz_io_set_mode(KzIO *io, KzIOMode mode)
{
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (io);
	priv->mode = mode;
}


static void
kz_io_set_buffer_mode (KzIO *io)
{
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (io);
	priv->buffer_mode = TRUE;
}


static gboolean
kz_io_is_buffer_mode (KzIO *io)
{
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (io);
	return priv->buffer_mode;
}


const gchar *
kz_io_get_buffer (KzIO *io)
{
	KzIOPrivate *priv = KZ_IO_GET_PRIVATE (io);
	return priv->buffer->str;
}


gdouble
kz_io_get_progress (KzIO *io)
{
	KzIOPrivate *priv;
	g_return_val_if_fail(KZ_IS_IO(io), 0);

	priv = KZ_IO_GET_PRIVATE (io);
	g_return_val_if_fail(priv->file_size, 0);

	return (gdouble)(priv->loaded_size / priv->file_size);
}


guint
kz_io_get_lastmodified (KzIO *io)
{
	KzIOPrivate *priv;
	g_return_val_if_fail(KZ_IS_IO(io), 0);

	priv = KZ_IO_GET_PRIVATE (io);
	return priv->last_modified;
}


gsize
kz_io_get_file_size (KzIO *io)
{
	KzIOPrivate *priv;
	g_return_val_if_fail(KZ_IS_IO(io), 0);

	priv = KZ_IO_GET_PRIVATE (io);
	return priv->file_size;
}


gsize
kz_io_get_loaded_size (KzIO *io)
{
	KzIOPrivate *priv;
	g_return_val_if_fail(KZ_IS_IO(io), 0);

	priv = KZ_IO_GET_PRIVATE (io);
	return priv->loaded_size;
}


KzIOMode
kz_io_get_mode(KzIO *io)
{
	KzIOPrivate *priv;
	
	priv = KZ_IO_GET_PRIVATE (io);
	return priv->mode;
}


void
kz_io_load_to_buffer (KzIO *io)
{
	g_return_if_fail(KZ_IS_IO(io));
	
	kz_io_set_mode(io, KZ_IO_READ);
	kz_io_set_buffer_mode(io);

	KZ_IO_GET_CLASS(io)->io_start(io);
}


void
kz_io_load_to_file (KzIO *io, const gchar *filename)
{
	KzIOPrivate *priv;
	
	g_return_if_fail(KZ_IS_IO(io));
	
	priv = KZ_IO_GET_PRIVATE (io);
	kz_io_set_mode(io, KZ_IO_READ);

	priv->localfile = g_strdup(filename);

	KZ_IO_GET_CLASS(io)->io_start(io);
}


void
kz_io_write (KzIO *io, const gchar *buffer)
{
	KzIOPrivate *priv;
	g_return_if_fail(KZ_IS_IO(io));
	g_return_if_fail(buffer && *buffer);
	
	priv = KZ_IO_GET_PRIVATE (io);
	kz_io_set_mode(io, KZ_IO_WRITE);

	priv->write_buffer = buffer;

	KZ_IO_GET_CLASS(io)->io_start(io);
}


void
kz_io_start (KzIO *io)
{
	KZ_IO_GET_CLASS(io)->io_start(io);
}


void
kz_io_stop (KzIO *io)
{
	KzIOPrivate *priv;
	g_return_if_fail(KZ_IS_IO(io));
	priv = KZ_IO_GET_PRIVATE (io);
	priv->cancel = TRUE;
	return;
}

#include <zlib.h>
#define OUTBUFSIZ 1024

static GString *
kz_io_decode_string(GString *string)
{
	z_stream z;
	gint status = Z_OK;
	GString *outstring;
	gchar outbuf[OUTBUFSIZ] = "";

	g_return_val_if_fail(string, NULL);

	z.zalloc = Z_NULL;
	z.zfree = Z_NULL;
	z.opaque = Z_NULL;
	z.next_in = (unsigned char*)string->str;
	z.avail_in = string->len;
	z.next_out = (unsigned char*)outbuf;
	z.avail_out = OUTBUFSIZ;

	/* windowBits+32 means to enable zlib and gzip decoding
	 * with automatic header detection. (see zlib.h) */
	if (inflateInit2(&z, MAX_WBITS + 32) != Z_OK) 
	{
		g_warning("inflateInit2: %s", z.msg);
		return NULL;
	}

	outstring = g_string_sized_new(string->len);

	while (status != Z_STREAM_END)
	{
		status = inflate(&z, Z_SYNC_FLUSH);
		if (status == Z_STREAM_END || status == Z_OK)
		{
			g_string_append_len(outstring, outbuf, OUTBUFSIZ - z.avail_out);
			z.next_out = (unsigned char*)outbuf;
			z.avail_out = OUTBUFSIZ;
		}
		else
		{
			g_warning("inflate: %s", z.msg);
			g_string_free(outstring, TRUE);
			outstring = NULL;
			break;
		}
	}

	/* XXX: should call inflate(&z, Z_FINISH) for checking errors? */

	status = inflateEnd(&z);
	if (status != Z_OK)
	{
		g_warning("inflateEnd: %s", z.msg);
		if (outstring)
			g_string_free(outstring, TRUE);
		outstring = NULL;
	}

	return outstring;
}

GIOStatus
kz_io_decode_buffer(KzIO *io, const gchar *content_encoding)
{
	KzIOPrivate *priv;
	GIOStatus status = G_IO_STATUS_EOF;
	GString *decoded = NULL;

	g_return_val_if_fail(KZ_IS_IO(io), status);
	if (!kz_io_is_buffer_mode(io))
	{
		g_warning("kz_io_decode_buffer: cannot decode io when io is not buffer mode");
		return status;
	}
	
	priv = KZ_IO_GET_PRIVATE (io);
	g_return_val_if_fail(content_encoding, status);
	g_return_val_if_fail(priv->buffer, status);

	if ((g_ascii_strcasecmp(content_encoding, "x-gzip") == 0) ||
	    (g_ascii_strcasecmp(content_encoding, "gzip") == 0) ||
	    (g_ascii_strcasecmp(content_encoding, "deflate") == 0))
	{
		decoded = kz_io_decode_string(priv->buffer);
	}

	if (decoded)
	{
		g_string_free(priv->buffer, TRUE);
		priv->buffer = decoded;
		/* reset buffer length */
		priv->loaded_size = decoded->len;
		priv->file_size = decoded->len;
	}

	return status;
}
