/* 
   Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Bastien Nocera
   Copyright (C) 2003, 2004 Colin Walters <walters@rhythmbox.org>

   The Gnome Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   The Gnome 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with the Gnome Library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301  USA.

   Author: Bastien Nocera <hadess@hadess.net>
 */

#include "config.h"

#include <string.h>
#include <glib.h>

#ifndef XPLAYER_PL_PARSER_MINI
#include <glib/gi18n-lib.h>

#include <gio/gio.h>

#include "xplayer-pl-parser.h"
#include "xplayer-pl-parser-pls.h"
#endif /* !XPLAYER_PL_PARSER_MINI */

#include "xplayer-pl-parser-mini.h"
#include "xplayer-pl-parser-lines.h"
#include "xplayer-pl-parser-private.h"

#ifndef XPLAYER_PL_PARSER_MINI

#define EXTINF "#EXTINF:"
#define EXTVLCOPT "#EXTVLCOPT"

static char *
xplayer_pl_parser_uri_to_dos (const char *uri, GFile *output)
{
	char *retval, *i;

	/* Get a relative URI if there is one */
	retval = xplayer_pl_parser_relative (output, uri);

	if (retval == NULL)
		retval = g_strdup (uri);

	/* Don't change URIs, but change smb:// */
	if (g_str_has_prefix (retval, "smb://") != FALSE) {
		char *tmp;
		tmp = g_strdup (retval + strlen ("smb:"));
		g_free (retval);
		retval = tmp;
	}

	if (strstr (retval, "://") != NULL)
		return retval;

	i = retval;
	while (*i != '\0')
	{
		if (*i == '/')
			*i = '\\';
		i++;
	}

	return retval;
}

gboolean
xplayer_pl_parser_save_m3u (XplayerPlParser    *parser,
                          XplayerPlPlaylist  *playlist,
                          GFile            *output,
                          gboolean          dos_compatible,
                          GError          **error)
{
        XplayerPlPlaylistIter iter;
	GFileOutputStream *stream;
	gboolean valid, success;
	char *buf;
	const char *cr;

	stream = g_file_replace (output, NULL, FALSE, G_FILE_CREATE_NONE, NULL, error);
	if (stream == NULL)
		return FALSE;

	cr = dos_compatible ? "\r\n" : "\n";

	buf = g_strdup_printf ("#EXTM3U%s", cr);
	success = xplayer_pl_parser_write_string (G_OUTPUT_STREAM (stream), buf, error);
	g_free (buf);
	if (success == FALSE)
		return FALSE;

        valid = xplayer_pl_playlist_iter_first (playlist, &iter);

        while (valid) {
		char *uri, *title, *path2;
		GFile *file;

                xplayer_pl_playlist_get (playlist, &iter,
                                       XPLAYER_PL_PARSER_FIELD_URI, &uri,
                                       XPLAYER_PL_PARSER_FIELD_TITLE, &title,
                                       NULL);

                valid = xplayer_pl_playlist_iter_next (playlist, &iter);

                if (!uri) {
                        g_free (title);
                        continue;
                }

                file = g_file_new_for_uri (uri);

		if (xplayer_pl_parser_scheme_is_ignored (parser, file) != FALSE) {
			g_object_unref (file);
			g_free (uri);
			g_free (title);
			continue;
		}
		g_object_unref (file);

		if (title) {
			buf = g_strdup_printf (EXTINF",%s%s", title, cr);
			success = xplayer_pl_parser_write_string (G_OUTPUT_STREAM (stream), buf, error);
			g_free (buf);
			if (success == FALSE) {
				g_free (title);
				g_free (uri);
				return FALSE;
			}
		}
		g_free (title);

		if (dos_compatible == FALSE) {
			char *tmp;

			tmp = xplayer_pl_parser_relative (output, uri);

			if (tmp == NULL && g_str_has_prefix (uri, "file:")) {
				path2 = g_filename_from_uri (uri, NULL, NULL);
			} else {
				path2 = tmp;
			}
		} else {
			path2 = xplayer_pl_parser_uri_to_dos (uri, output);
		}

		buf = g_strdup_printf ("%s%s", path2 ? path2 : uri, cr);
		g_free (path2);
		g_free (uri);

		success = xplayer_pl_parser_write_string (G_OUTPUT_STREAM (stream), buf, error);
		g_free (buf);

		if (success == FALSE)
			return FALSE;
	}

	g_object_unref (stream);

	return TRUE;
}

static void
xplayer_pl_parser_parse_ram_uri (XplayerPlParser *parser, const char *uri)
{
	char *mark, **params;
	GString *str;
	guint i, num_params;
	char *title, *author, *copyright, *abstract, *screensize, *mode, *start, *end;

	if (g_str_has_prefix (uri, "rtsp://") == FALSE
	    && g_str_has_prefix (uri, "pnm://") == FALSE) {
		xplayer_pl_parser_add_one_uri (parser, uri, NULL);
		return;
	}

	/* Look for "?" */
	mark = strstr (uri, "?");
	if (mark == NULL) {
		xplayer_pl_parser_add_one_uri (parser, uri, NULL);
		return;
	}

	if (mark[1] == '\0') {
		char *new_uri;

		new_uri = g_strndup (uri, mark + 1 - uri);
		xplayer_pl_parser_add_one_uri (parser, new_uri, NULL);
		g_free (new_uri);
		return;
	}

	title = author = copyright = abstract = screensize = mode = end = start = NULL;
	num_params = 0;

	str = g_string_new_len (uri, mark - uri);
	params = g_strsplit (mark + 1, "&", -1);
	for (i = 0; params[i] != NULL; i++) {
		if (g_str_has_prefix (params[i], "title=") != FALSE) {
			title = params[i] + strlen ("title=");
		} else if (g_str_has_prefix (params[i], "author=") != FALSE) {
			author = params[i] + strlen ("author=");
		} else if (g_str_has_prefix (params[i], "copyright=") != FALSE) {
			copyright = params[i] + strlen ("copyright=");
		} else if (g_str_has_prefix (params[i], "abstract=") != FALSE) {
			abstract = params[i] + strlen ("abstract=");
		} else if (g_str_has_prefix (params[i], "screensize=") != FALSE) {
			screensize = params[i] + strlen ("screensize=");
		} else if (g_str_has_prefix (params[i], "mode=") != FALSE) {
			mode = params[i] + strlen ("mode=");
		} else if (g_str_has_prefix (params[i], "end=") != FALSE) {
			end = params[i] + strlen ("end=");
		} else if (g_str_has_prefix (params[i], "start=") != FALSE) {
			start = params[i] + strlen ("start=");
		} else {
			if (num_params == 0)
				g_string_append_c (str, '?');
			else
				g_string_append_c (str, '&');
			g_string_append (str, params[i]);
			num_params++;
		}
	}

	xplayer_pl_parser_add_uri (parser,
				 XPLAYER_PL_PARSER_FIELD_URI, str->str,
				 XPLAYER_PL_PARSER_FIELD_TITLE, title,
				 XPLAYER_PL_PARSER_FIELD_AUTHOR, author,
				 XPLAYER_PL_PARSER_FIELD_COPYRIGHT, copyright,
				 XPLAYER_PL_PARSER_FIELD_ABSTRACT, abstract,
				 XPLAYER_PL_PARSER_FIELD_SCREENSIZE, screensize,
				 XPLAYER_PL_PARSER_FIELD_UI_MODE, mode,
				 XPLAYER_PL_PARSER_FIELD_STARTTIME, start,
				 XPLAYER_PL_PARSER_FIELD_ENDTIME, end,
				 NULL);

	g_string_free (str, TRUE);
	g_strfreev (params);
}

XplayerPlParserResult
xplayer_pl_parser_add_ram (XplayerPlParser *parser, GFile *file, XplayerPlParseData *parse_data, gpointer data)
{
	gboolean retval = XPLAYER_PL_PARSER_RESULT_UNHANDLED;
	char *contents, **lines;
	gsize size;
	guint i;

	if (g_file_load_contents (file, NULL, &contents, &size, NULL, NULL) == FALSE)
		return XPLAYER_PL_PARSER_RESULT_ERROR;

	lines = g_strsplit_set (contents, "\r\n", 0);
	g_free (contents);

	for (i = 0; lines[i] != NULL; i++) {
		/* Empty line */
		if (xplayer_pl_parser_line_is_empty (lines[i]) != FALSE)
			continue;

		retval = XPLAYER_PL_PARSER_RESULT_SUCCESS;

		/* Either it's a URI, or it has a proper path ... */
		if (strstr(lines[i], "://") != NULL
				|| lines[i][0] == G_DIR_SEPARATOR) {
			GFile *line_file;

			line_file = g_file_new_for_uri (lines[i]);
			/* .ram files can contain .smil entries */
			if (xplayer_pl_parser_parse_internal (parser, line_file, NULL, parse_data) != XPLAYER_PL_PARSER_RESULT_SUCCESS)
				xplayer_pl_parser_parse_ram_uri (parser, lines[i]);
			g_object_unref (line_file);
		} else if (strcmp (lines[i], "--stop--") == 0) {
			/* For Real Media playlists, handle the stop command */
			break;
		} else {
			//FIXME
#if 0
			char *base;

			/* Try with a base */
			base = xplayer_pl_parser_base_uri (uri);

			if (xplayer_pl_parser_parse_internal (parser, lines[i], base) != XPLAYER_PL_PARSER_RESULT_SUCCESS)
			{
				char *fullpath;
				fullpath = g_strdup_printf ("%s/%s", base, lines[i]);
				xplayer_pl_parser_parse_ram_uri (parser, fullpath);
				g_free (fullpath);
			}
			g_free (base);
#endif
		}
	}

	g_strfreev (lines);

	return retval;
}

static const char *
xplayer_pl_parser_get_extinfo_title (const char *extinfo)
{
	const char *res, *sep;

	if (extinfo == NULL)
		return NULL;

	/* It's bound to have an EXTINF if we have extinfo */
	res = extinfo + strlen(EXTINF);
	if (res[0] == '\0')
		return NULL;

	/* Handle ',' as a field separator */
	sep = strstr (res, ",");
	if (sep == NULL || sep[1] == '\0') {
		if (res[1] == '\0')
			return NULL;
		return res;
	}

	sep++;
	return sep;
}

static char *
xplayer_pl_parser_get_extinfo_length (const char *extinfo)
{
	char *res, **items;

	if (extinfo == NULL)
		return NULL;

	/* It's bound to have an EXTINF if we have extinfo */
	res = (char *) extinfo + strlen(EXTINF);
	if (res[0] == '\0')
		return NULL;

	/* Handle ',' as a field separator */
	items = g_strsplit (res, ",", 2);
	if (!items || !items[0] || *items[0] == '\0') {
		g_strfreev (items);
		return NULL;
	}
	res = g_strdup (items[0]);
	g_strfreev (items);
	return res;
}

XplayerPlParserResult
xplayer_pl_parser_add_m3u (XplayerPlParser *parser,
			 GFile *file,
			 GFile *base_file,
			 XplayerPlParseData *parse_data,
			 gpointer data)
{
	XplayerPlParserResult retval = XPLAYER_PL_PARSER_RESULT_UNHANDLED;
	char *contents, **lines;
	gsize size;
	guint i, num_lines;
	gboolean dos_mode = FALSE;
	const char *extinfo;
	char *pl_uri;

	if (g_file_load_contents (file, NULL, &contents, &size, NULL, NULL) == FALSE)
		return XPLAYER_PL_PARSER_RESULT_ERROR;

	/* .pls files with a .m3u extension, the nasties */
	if (g_str_has_prefix (contents, "[playlist]") != FALSE
			|| g_str_has_prefix (contents, "[Playlist]") != FALSE
			|| g_str_has_prefix (contents, "[PLAYLIST]") != FALSE) {
		retval = xplayer_pl_parser_add_pls_with_contents (parser, file, base_file, contents, parse_data);
		g_free (contents);
		return retval;
	}

	/* Try to use ISO-8859-1 if we don't have valid UTF-8,
	 * try to parse anyway if it's not ISO-8859-1 */
	if (g_utf8_validate (contents, -1, NULL) == FALSE) {
		char *fixed;
		fixed = g_convert (contents, -1, "UTF-8", "ISO8859-1", NULL, NULL, NULL);
		if (fixed != NULL) {
			g_free (contents);
			contents = fixed;
		}
	}

	/* is non-NULL if there's an EXTINF on a preceding line */
	extinfo = NULL;

	/* figure out whether we're a unix m3u or dos m3u */
	if (strstr(contents, "\x0d")) {
		dos_mode = TRUE;
	}

	lines = g_strsplit_set (contents, "\r\n", 0);
	g_free (contents);
	num_lines = g_strv_length (lines);
	/* We don't count the terminating NULL */
	num_lines--;

	/* Send out the playlist start and get crackin' */
	pl_uri = g_file_get_uri (file);
	xplayer_pl_parser_add_uri (parser,
				 XPLAYER_PL_PARSER_FIELD_IS_PLAYLIST, TRUE,
				 XPLAYER_PL_PARSER_FIELD_URI, pl_uri,
				 XPLAYER_PL_PARSER_FIELD_CONTENT_TYPE, "audio/x-mpegurl",
				 NULL);

	for (i = 0; lines[i] != NULL; i++) {
		const char *line;
		char *length;
		gint64 length_num = 0;

		line = lines[i];

		if (line[0] == '\0')
			continue;

		retval = XPLAYER_PL_PARSER_RESULT_SUCCESS;

		/* Ignore leading spaces */
		for (; g_ascii_isspace (line[0]); line++)
			;

		/* Ignore comments, but mark it if we have extra info */
		if (line[0] == '#') {
			if (extinfo == NULL && g_str_has_prefix (line, EXTINF) != FALSE)
				extinfo = line;
			continue;
		}

		length = xplayer_pl_parser_get_extinfo_length (extinfo);
		if (length != NULL)
			length_num = xplayer_pl_parser_parse_duration (length, xplayer_pl_parser_is_debugging_enabled (parser));
		g_free (length);

		/* Either it's a URI, or it has a proper path ... */
		if (strstr(line, "://") != NULL
				|| line[0] == G_DIR_SEPARATOR) {
			GFile *uri;

			uri = g_file_new_for_commandline_arg (line);
			if (length_num < 0 ||
			    xplayer_pl_parser_parse_internal (parser, uri, NULL, parse_data) != XPLAYER_PL_PARSER_RESULT_SUCCESS) {
				xplayer_pl_parser_add_one_uri (parser, line,
						xplayer_pl_parser_get_extinfo_title (extinfo));
			}
			g_object_unref (uri);
			extinfo = NULL;
		} else if (g_ascii_isalpha (line[0]) != FALSE
			   && g_str_has_prefix (line + 1, ":\\")) {
			/* Path relative to a drive on Windows, we need to use
			 * the base that was passed to us */
			GFile *uri;

			lines[i] = g_strdelimit (lines[i], "\\", '/');
			/* + 2, skip drive letter */
			uri = g_file_get_child (base_file, line + 2);
			xplayer_pl_parser_add_one_file (parser, uri,
						     xplayer_pl_parser_get_extinfo_title (extinfo));
			g_object_unref (uri);
			extinfo = NULL;
		} else if (line[0] == '\\' && line[1] == '\\') {
			/* ... Or it's in the windows smb form
			 * (\\machine\share\filename), Note drive names
			 * (C:\ D:\ etc) are unhandled (unknown base for
			 * drive letters) */
		        char *tmpuri;

			lines[i] = g_strdelimit (lines[i], "\\", '/');
			tmpuri = g_strjoin (NULL, "smb:", line, NULL);

			xplayer_pl_parser_add_one_uri (parser, line,
					xplayer_pl_parser_get_extinfo_title (extinfo));
			extinfo = NULL;

			g_free (tmpuri);
		} else {
			/* Try with a base */
			GFile *uri, *_base_file;
			char sep;

			_base_file = g_file_get_parent (file);
			sep = (dos_mode ? '\\' : '/');
			if (sep == '\\')
				lines[i] = g_strdelimit (lines[i], "\\", '/');
			uri = g_file_get_child (_base_file, line);
			g_object_unref (_base_file);
			xplayer_pl_parser_add_one_file (parser, uri,
						     xplayer_pl_parser_get_extinfo_title (extinfo));
			g_object_unref (uri);
			extinfo = NULL;
		}
	}

	g_strfreev (lines);

	xplayer_pl_parser_playlist_end (parser, pl_uri);
	g_free (pl_uri);

	return retval;
}

XplayerPlParserResult
xplayer_pl_parser_add_m4u (XplayerPlParser *parser,
			 GFile *file,
			 GFile *base_file,
			 XplayerPlParseData *parse_data,
			 gpointer data)
{
	return xplayer_pl_parser_add_m3u (parser, file,
					base_file, parse_data, data);
}

XplayerPlParserResult
xplayer_pl_parser_add_ra (XplayerPlParser *parser,
			GFile *file,
			GFile *base_file,
			XplayerPlParseData *parse_data,
			gpointer data)
{
	if (data == NULL || xplayer_pl_parser_is_uri_list (data, strlen (data)) == NULL) {
		xplayer_pl_parser_add_one_file (parser, file, NULL);
		return XPLAYER_PL_PARSER_RESULT_SUCCESS;
	}

	return xplayer_pl_parser_add_ram (parser, file, parse_data, NULL);
}

#endif /* !XPLAYER_PL_PARSER_MINI */

#define CHECK_LEN if (i >= len) { return NULL; }

const char *
xplayer_pl_parser_is_uri_list (const char *data, gsize len)
{
	guint i = 0;

	/* Find the first bits of text */
	while (data[i] == '\n' || data[i] == '\t' || data[i] == ' ') {
		i++;
		CHECK_LEN;
	}
	CHECK_LEN;

	/* scheme always starts with a letter */
	if (g_ascii_isalpha (data[i]) == FALSE)
		return FALSE;
	while (g_ascii_isalnum (data[i]) != FALSE) {
		i++;
		CHECK_LEN;
	}

	CHECK_LEN;

	/* First non-alphanum character should be a ':' */
	if (data[i] != ':')
		return FALSE;
	i++;
	CHECK_LEN;

	if (data[i] != '/')
		return NULL;
	i++;
	CHECK_LEN;

	if (data[i] != '/')
		return NULL;

	return TEXT_URI_TYPE;
}

