#include <gst/player/player.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <math.h>
#include <stdlib.h>
#include "gnome-voice-file.h"

GList *voice_stations;

static void
gnome_voice_file_parser (VoiceInfo *info,
			 xmlDocPtr doc,
			 xmlNodePtr cur)
{
	GstPlayer *player;
	xmlChar *lon, *lat;
        xmlNodePtr sub;
	g_return_if_fail (info != NULL);
	g_return_if_fail (doc != NULL);
	g_return_if_fail (cur != NULL);
	info->name = (gchar *)xmlGetProp(cur, (const xmlChar *)"name");
	g_print ("info->name = %s\n", info->name);
	info->uri = (gchar *)xmlGetProp(cur, (const xmlChar *)"uri");
	g_print ("info->uri = %s\n", info->uri);
	sub = cur->xmlChildrenNode;
	while (sub != NULL) {
		if ((!xmlStrcmp (sub->name, (const xmlChar *) "location"))) {
			LocationInfo *location = g_new0 (LocationInfo, 1);
			info->location = location;
			info->location->city = (gchar *) xmlNodeListGetString (sub, sub->xmlChildrenNode, 1);
			g_print ("location:city:%s\n", info->location->city);
		}
		if ((!xmlStrcmp (sub->name, (const xmlChar *) "stream"))) {
			StreamInfo *stream = g_new0 (StreamInfo, 1);
			info->stream = stream;
			info->stream->uri = (gchar *) xmlNodeListGetString (sub, sub->xmlChildrenNode, 1);
			g_print ("stream:uri:%s\n", info->stream->uri);
				/* Create the voice player */
			player = gst_player_new (NULL, gst_player_g_main_context_signal_dispatcher_new(NULL));
			gst_player_set_uri (GST_PLAYER (player), info->stream->uri);
			gst_player_play(GST_PLAYER (player));

	}
		sub = sub->next;
	}
	return;
}

VoiceInfo *
gnome_voice_file_loader (VoiceInfo *head,
			 char *filename)
{
	xmlDocPtr doc = NULL;
	xmlNodePtr cur = NULL;
	VoiceInfo *curr = NULL;
	VoiceInfo *mem_station = NULL;
	char *version;

	g_return_val_if_fail (filename != NULL, NULL);
	doc = xmlReadFile (filename, NULL, 0);
	if (doc == NULL) {
		perror ("xmlParseFile");
		xmlFreeDoc (doc);
		return NULL;
	}
	cur = xmlDocGetRootElement (doc);
	if (cur == NULL) {
		fprintf (stderr, "Empty document\n");
		xmlFreeDoc (doc);
		return NULL;
	}
	if (xmlStrcmp (cur->name, (const xmlChar *) "voice")) {
		fprintf (stderr,
			 "Document of wrong type, root node != voice\n");
		xmlFreeDoc (doc);
		return NULL;
	}

	version = (gchar *)xmlGetProp(cur, (const xmlChar *)"version");

	g_print ("Valid Voice %s XML document... Parsing stations...\n",
		  version);

	cur = cur->xmlChildrenNode;
	while (cur != NULL) {
		if ((!strcasecmp (cur->name, (const xmlChar *) "station"))) {
		        g_print ("Found a new station.\n");
			curr = g_new0(VoiceInfo, 1);
			mem_station = g_new0(VoiceInfo, 1);
			gnome_voice_file_parser (curr, doc, cur);
			curr->next = head;
			head = curr;
			mem_station = head;
			voice_stations = g_list_append (voice_stations, (VoiceInfo *)mem_station);
		}
		cur = cur->next;
	}
	xmlFreeDoc (doc);
	return curr;
}
