/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: statistics.cpp,v 1.6.2.4 2004/10/18 18:53:31 rggammon Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

#include "hxcom.h"
#include "hxwintyp.h"
#include "hxcore.h"

#include "statistics.h"
#include "commonapp.h"
#include "hxstatisticsobserver.h"
#include "hxplayer-i18n.h"
#include "hxbandwidthgraph.h"

#include <gtk/gtk.h>

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define STATISTICS_UPDATE_INTERVAL 1000 /* in ms */

extern "C"
{
GtkWidget* hsd_create_bandwidth_graph(gchar *widget_name,
                                      gchar *string1,
                                      gchar *string2,
                                      gint int1,
                                      gint int2);

void hsd_stream_combo_changed(GtkEntry* entry);
}

/* Per-player statistics */
enum
{
    STATISTIC_UI_CLIP_BANDWIDTH = 0,
    STATISTIC_UI_CURRENT_BANDWIDTH,
    STATISTIC_UI_MIN_BANDWIDTH,
    STATISTIC_UI_MAX_BANDWIDTH,
    STATISTIC_UI_AVERAGE_BANDWIDTH,
    STATISTIC_UI_RECEIVED,
    STATISTIC_UI_RECEIVED_PERCENT,
    STATISTIC_UI_RECOVERED,
    STATISTIC_UI_RECOVERED_PERCENT,
    STATISTIC_UI_TOTAL_RECEIVED,
    STATISTIC_UI_TOTAL_RECEIVED_PERCENT,
    STATISTIC_UI_LOST,
    STATISTIC_UI_LOST_PERCENT,
    STATISTIC_UI_LATE,
    STATISTIC_UI_LATE_PERCENT,
    STATISTIC_UI_TOTAL_MISSED,
    STATISTIC_UI_TOTAL_MISSED_PERCENT,
    STATISTIC_UI_RESEND_REQUESTED,
    STATISTIC_UI_RESEND_RECEIVED,
    STATISTIC_UI_LOW_LATENCY,
    STATISTIC_UI_AVERAGE_LATENCY,
    STATISTIC_UI_HIGH_LATENCY,
    STATISTIC_UI_LOST30,               
    STATISTIC_UI_LOST30_PERCENT,

    STATISTIC_UI_COUNT
};

/* Per-source statistics */
enum
{
    STATISTIC_UI_SOURCE_SERVER_INFO = 0,
    STATISTIC_UI_SOURCE_RENDERER_CODEC_NAME,
    STATISTIC_UI_SOURCE_CLIP_BANDWIDTH,
    STATISTIC_UI_SOURCE_TRANSPORT_MODE,
    STATISTIC_UI_SOURCE_RENDERER_CODEC_RATE,
    STATISTIC_UI_SOURCE_RENDERER_FRAMES_DISPLAYED,
    STATISTIC_UI_SOURCE_RENDERER_CURRENT_FRAME_RATE,
    STATISTIC_UI_SOURCE_RENDERER_FRAMES_LOST,
    STATISTIC_UI_SOURCE_RENDERER_POST_FILTER,
    STATISTIC_UI_SOURCE_RENDERER_FRAMES_DROPPED,   

    /* These stats aren't reported in the other players: 
       Duplicate
       Normal
       Total30
       BufferingMode
       OutOfOrder
    */
        
    STATISTIC_UI_SOURCE_COUNT
};

typedef struct _HXStatisticsDialog
{
    GtkLabel* main  [STATISTIC_UI_COUNT];
    GtkLabel* source[STATISTIC_UI_SOURCE_COUNT];
    GladeXML* xml;
    HXPlayer* player;
    HXBandwidthGraph* bandwidth_graph;
    
    /* These are updated by statistics observers */
    gint max_bandwidth;
    gint min_bandwidth;

    gboolean max_bandwidth_is_set;
    gboolean min_bandwidth_is_set;

    HXStatisticsObserver* bandwidth_observer;
    HXStatisticsObserver* advanced_observer;

    GtkCombo* streams_combo;

    gint source_count;
    GArray* stream_counts_array;

    gint current_source;
    gint current_stream;
    
    gint clip_bandwidth_handler;
    gint play_handler;
    guint timer_id;

} HXStatisticsDialog;

static void
update_bandwidth(HXStatisticsDialog* info, GValue* value)
{
    gint bandwidth;

    bandwidth = g_value_get_int(value);

    if(bandwidth < info->min_bandwidth || !info->min_bandwidth_is_set)
    {
        info->min_bandwidth_is_set = TRUE;
        info->min_bandwidth = bandwidth;
    }

    if(bandwidth > info->max_bandwidth || !info->max_bandwidth_is_set)
    {
        info->max_bandwidth_is_set = TRUE;
        info->max_bandwidth = bandwidth;        
    }

    if(info->bandwidth_graph)
    {
        hx_bandwidth_graph_add_value(info->bandwidth_graph, bandwidth);        
    }
}


static void
hsd_update_bandwidth(GObject*     /* observer */,
                     const gchar* /* key */,
                     GValue*      value,
                     gpointer     data)
{
    HXStatisticsDialog* info;

    info = (HXStatisticsDialog*) data;

    update_bandwidth(info, value);
}

static void
hsd_play(HXStatisticsDialog* info)
{
    gboolean result;
    GValue value;
    memset(&value, 0, sizeof(value));
    
    info->min_bandwidth_is_set = FALSE;
    info->max_bandwidth_is_set = FALSE;

    result = hx_player_get_statistic(info->player, "CurrentBandwidth", &value);
    if(result)
    {
        update_bandwidth(info, &value);
        g_value_unset(&value);
    }
}

static gboolean
get_statistic_dialog_info(GladeXML* xml, HXPlayer* player, HXStatisticsDialog* info)
{
    guint i;
    
    info->player = player;
    info->xml = xml;

    info->streams_combo = GTK_COMBO(glade_xml_get_widget (info->xml, "hsd_stream_combo"));
    info->bandwidth_graph = HX_BANDWIDTH_GRAPH(glade_xml_get_widget (info->xml, "hsd_bandwidth_graph"));

    g_return_val_if_fail(info->streams_combo &&
                         info->bandwidth_graph,
                         FALSE);
    
    info->stream_counts_array = g_array_new(TRUE, TRUE, sizeof(guint));
        
    info->main[STATISTIC_UI_CLIP_BANDWIDTH   ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_clip_bandwidth"));
    info->main[STATISTIC_UI_CURRENT_BANDWIDTH] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_current_bandwidth"));
    info->main[STATISTIC_UI_MIN_BANDWIDTH    ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_min_bandwidth"));
    info->main[STATISTIC_UI_MAX_BANDWIDTH    ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_max_bandwidth"));
    info->main[STATISTIC_UI_AVERAGE_BANDWIDTH] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_average_bandwidth"));
    info->main[STATISTIC_UI_RECEIVED         ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_received"));         
    info->main[STATISTIC_UI_RECEIVED_PERCENT ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_received_percent"));         
    info->main[STATISTIC_UI_RECOVERED        ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_recovered"));
    info->main[STATISTIC_UI_RECOVERED_PERCENT] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_recovered_percent"));
    info->main[STATISTIC_UI_TOTAL_RECEIVED   ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_total_received"));
    info->main[STATISTIC_UI_TOTAL_RECEIVED_PERCENT] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_total_received_percent"));
    info->main[STATISTIC_UI_LOST             ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_lost"));
    info->main[STATISTIC_UI_LOST_PERCENT     ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_lost_percent"));
    info->main[STATISTIC_UI_LATE             ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_late"));
    info->main[STATISTIC_UI_LATE_PERCENT     ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_late_percent"));
    info->main[STATISTIC_UI_TOTAL_MISSED     ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_total_missed"));
    info->main[STATISTIC_UI_TOTAL_MISSED_PERCENT] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_total_missed_percent"));
    info->main[STATISTIC_UI_RESEND_REQUESTED ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_resend_requested"));
    info->main[STATISTIC_UI_RESEND_RECEIVED  ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_resend_received"));   
    info->main[STATISTIC_UI_LOW_LATENCY      ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_low_latency"));       
    info->main[STATISTIC_UI_AVERAGE_LATENCY  ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_average_latency"));   
    info->main[STATISTIC_UI_HIGH_LATENCY     ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_high_latency"));   
    info->main[STATISTIC_UI_LOST30           ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_lost_30"));
    info->main[STATISTIC_UI_LOST30_PERCENT   ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_lost_30_percent"));
                                              
    info->source[STATISTIC_UI_SOURCE_SERVER_INFO                ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_server_info"));
    info->source[STATISTIC_UI_SOURCE_RENDERER_CODEC_NAME        ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_renderer_codec_name"));
    info->source[STATISTIC_UI_SOURCE_CLIP_BANDWIDTH             ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_clip_bandwidth"));
    info->source[STATISTIC_UI_SOURCE_TRANSPORT_MODE             ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_transport_mode"));
    info->source[STATISTIC_UI_SOURCE_RENDERER_CODEC_RATE        ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_renderer_codec_frame_rate"));
    info->source[STATISTIC_UI_SOURCE_RENDERER_FRAMES_DISPLAYED  ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_renderer_frames_displayed"));
    info->source[STATISTIC_UI_SOURCE_RENDERER_CURRENT_FRAME_RATE] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_renderer_current_frame_rate"));
    info->source[STATISTIC_UI_SOURCE_RENDERER_FRAMES_LOST       ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_renderer_frames_lost"));
    info->source[STATISTIC_UI_SOURCE_RENDERER_POST_FILTER       ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_renderer_post_filter"));
    info->source[STATISTIC_UI_SOURCE_RENDERER_FRAMES_DROPPED    ] = GTK_LABEL(glade_xml_get_widget (info->xml, "hsd_source_renderer_frames_dropped"));

    for(i = 0; i < STATISTIC_UI_COUNT; i++)
    {
        g_return_val_if_fail(info->main[i], FALSE);
    }
    
    for(i = 0; i < STATISTIC_UI_SOURCE_COUNT; i++)
    {        
        g_return_val_if_fail(info->source[i], FALSE);
    }

    return TRUE;
}

GtkWidget*
hsd_create_bandwidth_graph(gchar*,
                           gchar*,
                           gchar*,
                           gint,
                           gint)
{
    GtkWidget* bandwidth_graph;

    bandwidth_graph = hx_bandwidth_graph_new();
    
    return bandwidth_graph;
}

static void
update_source_stream_count(HXPlayer* player,
                           gint*  sources_count_ptr,
                           GArray** stream_counts_ptr,
                           gboolean* changed_ptr)
{
    gint source = 0;
    gint stream = 0;
    gchar* stream_id;
    gboolean result;
    GValue value;

    memset(&value, 0, sizeof(value));
        
    for(source = 0; ; source++)
    {        
        for(stream = 0; ; stream++)
        {
            stream_id = g_strdup_printf("Source%d.Stream%d", source, stream);

#if 0            
            result = hx_player_get_statistic(player, stream_id, &value);
#else
            // XXXRGG: Hack! Can't check for composite statistics right now, so
            // append Total, a randomly chosen child that should exist
            gchar stream_id_non_composite_hack[256];
            snprintf(stream_id_non_composite_hack,
                     sizeof(stream_id_non_composite_hack),
                     "%s.Total",
                     stream_id);

            result = hx_player_get_statistic(player,
                                             stream_id_non_composite_hack,
                                             &value);
#endif
            g_free(stream_id);
            
            if(result)
            {
                guint sources_count = source + 1;
                g_value_unset(&value);

                if((source + 1) > *sources_count_ptr)
                {
                    *sources_count_ptr = sources_count;
                    *changed_ptr = TRUE;
                }
            }
            else
            {
                guint stream_count = stream;
                guint old_stream_count = g_array_index(*stream_counts_ptr,
                                                       guint,
                                                       source);                
                if(stream_count != old_stream_count)
                {
                    *changed_ptr = TRUE;
                    g_array_insert_val(*stream_counts_ptr, source, stream);
                }

                break;
            }
        }

        if(!result && stream == 0)
        {
            break;
        }
    }
}

static void
update_statistics(HXStatisticsDialog* info)
{
    gboolean result;
    GValue value;
    gint val;
    const gchar* str_val;
    gchar* formatted_str;
    memset(&value, 0, sizeof(value));
    gint total = 0;
    gint received = 0;
    gint recovered = 0;
    gint lost = 0;
    gint late = 0;
    gint total30 = 0;
    gint lost30 = 0;
    gboolean total_is_set = FALSE;
    gboolean received_is_set = FALSE;
    gboolean recovered_is_set = FALSE;
    gboolean lost_is_set = FALSE;
    gboolean late_is_set = FALSE;
    gboolean total30_is_set = FALSE;
    gboolean lost30_is_set = FALSE;
    GString* stream_prop = NULL;
    gboolean streams_combo_dirty = FALSE;

    hx_bandwidth_graph_update(info->bandwidth_graph);

    update_source_stream_count(info->player,
                               &info->source_count,
                               &info->stream_counts_array,
                               &streams_combo_dirty);
    
    /* Build streams combo */
    if(streams_combo_dirty)
    {
        GList* items = NULL;
        gint i, j;

        for(i = 0; i < info->source_count; i++)
        {
            gint streams_count = g_array_index(info->stream_counts_array,
                                               guint,
                                               i);
            
            for(j = 0; j < streams_count; j++)
            {
                gchar* str;
                str = g_strdup_printf("Stream%d.Source%d", i, j);
                items = g_list_append(items, str);
            }
        }

        if(items)
        {
            gtk_combo_set_popdown_strings(info->streams_combo, items);
            gtk_widget_set_sensitive(GTK_WIDGET(info->streams_combo), TRUE);
        }
        else
        {
            items = g_list_append(items, g_strdup(""));
            gtk_combo_set_popdown_strings(info->streams_combo, items);
            gtk_widget_set_sensitive(GTK_WIDGET(info->streams_combo), FALSE);
        }

        g_list_foreach(items, (GFunc)g_free, NULL);
        g_list_free(items);
    }
    
    result = hx_player_get_statistic(info->player, "Total", &value);
    if(result)
    {
        total = g_value_get_int(&value);
        total_is_set = TRUE;
        g_value_unset(&value);
    }
    
    result = hx_player_get_statistic(info->player, "ClipBandwidth", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        formatted_str = g_strdup_printf("%.1f Kbps", (gdouble)val / 1000.0);
        gtk_label_set_text(info->main[STATISTIC_UI_CLIP_BANDWIDTH], formatted_str);
        g_free(formatted_str);
        g_value_unset(&value);
    }
    else
    { 
        gtk_label_set_text(info->main[STATISTIC_UI_CLIP_BANDWIDTH], "---");
    }

    result = hx_player_get_statistic(info->player, "CurrentBandwidth", &value);
    if(result)
    {
        val = g_value_get_int(&value);

        if(info->bandwidth_graph)
        {
            /* Update bandwidth graph too. */
            hx_bandwidth_graph_add_value(info->bandwidth_graph, val);        
        }

        formatted_str = g_strdup_printf("%.1f Kbps", (gdouble)val / 1000.0);
        gtk_label_set_text(info->main[STATISTIC_UI_CURRENT_BANDWIDTH], formatted_str);
        g_free(formatted_str);
        g_value_unset(&value);
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_CURRENT_BANDWIDTH], "---");
    }

    if(info->min_bandwidth_is_set)
    {
        formatted_str = g_strdup_printf("%.1f Kbps", (gdouble)info->min_bandwidth / 1000.0);
        gtk_label_set_text(info->main[STATISTIC_UI_MIN_BANDWIDTH], formatted_str);
        g_free(formatted_str);
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_MIN_BANDWIDTH], "---");
    }

    if(info->max_bandwidth_is_set)
    {
        formatted_str = g_strdup_printf("%.1f Kbps", (gdouble)info->max_bandwidth / 1000.0);
        gtk_label_set_text(info->main[STATISTIC_UI_MAX_BANDWIDTH], formatted_str);
        g_free(formatted_str);
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_MAX_BANDWIDTH], "---");
    }    

    result = hx_player_get_statistic(info->player, "AverageBandwidth", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%.1f Kbps", (gdouble)val / 1000.0);
        gtk_label_set_text(info->main[STATISTIC_UI_AVERAGE_BANDWIDTH], formatted_str);
        g_free(formatted_str);
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_AVERAGE_BANDWIDTH], "---");        
    }

    result = hx_player_get_statistic(info->player, "Received", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_RECEIVED], formatted_str);
        g_free(formatted_str);

        received = val;
        received_is_set = TRUE;
        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_RECEIVED], "---");        
    }

    
    result = hx_player_get_statistic(info->player, "Recovered", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_RECOVERED], formatted_str);
        g_free(formatted_str);

        recovered = val;
        recovered_is_set = TRUE;
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_RECOVERED], "---");        
    }

    if(recovered_is_set && received_is_set)
    {
        formatted_str = g_strdup_printf("%d", recovered + received);
        gtk_label_set_text(info->main[STATISTIC_UI_TOTAL_RECEIVED], formatted_str);
        g_free(formatted_str);
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_TOTAL_RECEIVED], "---");        
    }

    
    if(total_is_set && received_is_set)
    {
        gdouble percent = 0;
                
        if(total > 0)
        {
            percent = 100.0 * (gdouble)(received) / total;
        }
        
        formatted_str = g_strdup_printf("(%.2f%%)", percent);
        gtk_label_set_text(info->main[STATISTIC_UI_RECEIVED_PERCENT], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_RECEIVED_PERCENT], "");
    }
    
    if(total_is_set && recovered_is_set)
    {
        gdouble percent = 0;
                
        if(total > 0)
        {
            percent = 100.0 * (gdouble)(recovered) / total;
        }
        
        formatted_str = g_strdup_printf("(%.2f%%)", percent);
        gtk_label_set_text(info->main[STATISTIC_UI_RECOVERED_PERCENT], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_RECOVERED_PERCENT], "---");
    }

    if(total_is_set && recovered_is_set && received_is_set)
    {
        gdouble percent = 0;
                
        if(total > 0)
        {
            percent = 100.0 * (gdouble)(received + recovered) / total;
        }
        
        formatted_str = g_strdup_printf("(%.2f%%)", percent);
        gtk_label_set_text(info->main[STATISTIC_UI_TOTAL_RECEIVED_PERCENT], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_TOTAL_RECEIVED_PERCENT], "---");
    }
    
    result = hx_player_get_statistic(info->player, "Lost", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_LOST], formatted_str);
        g_free(formatted_str);

        lost = val;
        lost_is_set = TRUE;
        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_LOST], "---");        
    }

    result = hx_player_get_statistic(info->player, "Late", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_LATE], formatted_str);
        g_free(formatted_str);

        late = val;
        late_is_set = TRUE;
        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_LATE], "---");        
    }

    if(lost_is_set && late_is_set)
    {
        formatted_str = g_strdup_printf("%d", lost + late);
        gtk_label_set_text(info->main[STATISTIC_UI_TOTAL_MISSED], formatted_str);
        g_free(formatted_str);

    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_TOTAL_MISSED], "---");        
    }

    if(total_is_set && lost_is_set)
    {
        gdouble percent = 0;
                
        if(total > 0)
        {
            percent = 100.0 * (gdouble)(lost) / total;
        }
        
        formatted_str = g_strdup_printf("(%.2f%%)", percent);
        gtk_label_set_text(info->main[STATISTIC_UI_LOST_PERCENT], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_LOST_PERCENT], "---");
    }
    
    if(total_is_set && late_is_set)
    {
        gdouble percent = 0;
                
        if(total > 0)
        {
            percent = 100.0 * (gdouble)(late) / total;
        }
        
        formatted_str = g_strdup_printf("(%.2f%%)", percent);
        gtk_label_set_text(info->main[STATISTIC_UI_LATE_PERCENT], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_LATE_PERCENT], "---");
    }

    if(total_is_set && lost_is_set && late_is_set)
    {
        gdouble percent = 0;
                
        if(total > 0)
        {
            percent = 100.0 * (gdouble)(lost + late) / total;
        }
        
        formatted_str = g_strdup_printf("(%.2f%%)", percent);
        gtk_label_set_text(info->main[STATISTIC_UI_TOTAL_MISSED_PERCENT], formatted_str);
        g_free(formatted_str);
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_TOTAL_MISSED_PERCENT], "---");
    }

    result = hx_player_get_statistic(info->player, "ResendRequested", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_RESEND_REQUESTED], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_RESEND_REQUESTED], "---");        
    }

    result = hx_player_get_statistic(info->player, "ResendReceived", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_RESEND_RECEIVED], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_RESEND_RECEIVED], "---");        
    }
    
    result = hx_player_get_statistic(info->player, "LowLatency", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_LOW_LATENCY], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_LOW_LATENCY], "---");        
    }

    result = hx_player_get_statistic(info->player, "AverageLatency", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_AVERAGE_LATENCY], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_AVERAGE_LATENCY], "---");        
    }

    result = hx_player_get_statistic(info->player, "HighLatency", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_HIGH_LATENCY], formatted_str);
        g_free(formatted_str);
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_HIGH_LATENCY], "---");        
    }

    result = hx_player_get_statistic(info->player, "Total30", &value);
    if(result)
    {
        total30 = g_value_get_int(&value);
        g_value_unset(&value);
        total30_is_set = TRUE;
    }
    
    result = hx_player_get_statistic(info->player, "Lost30", &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->main[STATISTIC_UI_HIGH_LATENCY], formatted_str);
        g_free(formatted_str);

        lost30_is_set = TRUE;
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_LOST30], "---");        
    }

    if(total30_is_set && lost30_is_set)
    {
        gdouble percent = 0;
                
        if(total30 > 0)
        {
            percent = 100.0 * (gdouble)lost30 / (gdouble)total30;
        }
        
        formatted_str = g_strdup_printf("(%.2f%%)", percent);
        gtk_label_set_text(info->main[STATISTIC_UI_LOST30_PERCENT], formatted_str);
        g_free(formatted_str);
    }
    else
    {
        gtk_label_set_text(info->main[STATISTIC_UI_LOST30_PERCENT], "---");
    }

    stream_prop = g_string_new("");
    
    g_string_printf(stream_prop, "Source%d.ServerInfo", info->current_source);
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        str_val = g_value_get_string(&value);
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_SERVER_INFO], str_val);
        g_value_unset(&value);
    }
    else
    {
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_SERVER_INFO], "---");        
    }
    
    // Codec is either CodecName or Codec - CodecText
    g_string_printf(stream_prop, "Source%d.Stream%d.Renderer.CodecName",
                    info->current_source,
                    info->current_stream);
                                              
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        str_val = g_value_get_string(&value);
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_CODEC_NAME], str_val);
        g_value_unset(&value);
    }
    else
    {
        // Try Codec (CodecText)
        gchar* codec = NULL;
        gchar* codec_text = NULL;

        g_string_printf(stream_prop, "Source%d.Stream%d.Renderer.Codec",
                        info->current_source,
                        info->current_stream);
        result = hx_player_get_statistic(info->player, stream_prop->str, &value);
        if(result)
        {
            codec = g_strdup(g_value_get_string(&value));
            g_value_unset(&value);
        }

        g_string_printf(stream_prop, "Source%d.Stream%d.Renderer.CodecText",
                        info->current_source,
                        info->current_stream);
        result = hx_player_get_statistic(info->player, stream_prop->str, &value);
        if(result)
        {
            codec_text = g_strdup(g_value_get_string(&value));
            g_value_unset(&value);
        }

        if(codec && codec_text)
        {
            formatted_str = g_strdup_printf("%s (%s)", codec, codec_text);
        }
        else if(codec)
        {
            formatted_str = g_strdup(codec);
        }
        else if(codec_text)
        {
            formatted_str = g_strdup(codec_text);
        }
        else
        {
            formatted_str = g_strdup("---");
        }

        if(codec)
        {
            g_free(codec);
        }

        if(codec_text)
        {
            g_free(codec_text);
        }
        
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_CODEC_NAME], formatted_str);
        g_free(formatted_str);        
    }

    g_string_printf(stream_prop, "Source%d.Stream%d.ClipBandwidth",
                    info->current_source,
                    info->current_stream);
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        val = g_value_get_int(&value);
        formatted_str = g_strdup_printf("%.1f Kbps", (gdouble)val / 1000.0);
        g_value_unset(&value);
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_CLIP_BANDWIDTH], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_CLIP_BANDWIDTH], "---");        
    }

    g_string_printf(stream_prop, "Source%d.TransportMode",
                    info->current_source);
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        str_val = g_value_get_string(&value);
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_TRANSPORT_MODE], str_val);
        g_value_unset(&value);
    }
    else
    {
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_TRANSPORT_MODE], _("Unknown"));        
    }
    
    g_string_printf(stream_prop, "Source%d.Stream%d.Renderer.CodecRate",
                    info->current_source,
                    info->current_stream);
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        str_val = g_value_get_string(&value);
        formatted_str = g_strdup_printf("%s fps", str_val);
        g_value_unset(&value);
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_CODEC_RATE], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_CODEC_RATE], "---");
    }

    g_string_printf(stream_prop, "Source%d.Stream%d.Renderer.FramesDisplayed",
                    info->current_source,
                    info->current_stream);
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        str_val = g_value_get_string(&value);
        formatted_str = g_strdup_printf("%s%%", str_val);
        g_value_unset(&value);
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_FRAMES_DISPLAYED], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_FRAMES_DISPLAYED], "---");
    }


    g_string_printf(stream_prop, "Source%d.Stream%d.Renderer.CurrentFrameRate",
                    info->current_source,
                    info->current_stream);
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        str_val = g_value_get_string(&value);
        formatted_str = g_strdup_printf("%s fps", str_val);
        g_value_unset(&value);
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_CURRENT_FRAME_RATE], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_CURRENT_FRAME_RATE], "---");
    }

    g_string_printf(stream_prop, "Source%d.Stream%d.Renderer.FramesLost",
                    info->current_source,
                    info->current_stream);
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_FRAMES_LOST], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_FRAMES_LOST], "---");
    }
    
    g_string_printf(stream_prop, "Source%d.Stream%d.Renderer.PostFilter",
                    info->current_source,
                    info->current_stream);
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        
        if(val)
        {
            gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_POST_FILTER], _("ON"));
        }
        else
        {
            gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_POST_FILTER], _("OFF"));
        }
    }
    else
    {
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_POST_FILTER], "---");
    }

    g_string_printf(stream_prop, "Source%d.Stream%d.Renderer.FramesDropped",
                    info->current_source,
                    info->current_stream);
    result = hx_player_get_statistic(info->player, stream_prop->str, &value);
    if(result)
    {
        val = g_value_get_int(&value);
        g_value_unset(&value);
        formatted_str = g_strdup_printf("%d", val);
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_FRAMES_DROPPED], formatted_str);
        g_free(formatted_str);        
    }
    else
    {
        gtk_label_set_text(info->source[STATISTIC_UI_SOURCE_RENDERER_FRAMES_DROPPED], "---");
    }
    
    g_string_free(stream_prop, TRUE);
}   

static gboolean
hsd_update_statistics(gpointer data)
{
    HXStatisticsDialog* info = (HXStatisticsDialog*)data;

    update_statistics(info);
    
    return TRUE; // don't remove
}

void
hsd_stream_combo_changed(GtkEntry* entry)
{
    /* GtkCombo's suck. Move this to GtkComboBox when our gtk baseline moves up. */
    HXStatisticsDialog* info;
    GtkWidget* toplevel;
    const gchar* text;
    guint source_len = sizeof("Source") - 1;
    guint stream_len = sizeof("Stream") - 1;

    toplevel = hxcommon_get_toplevel_widget_no_menus(GTK_WIDGET(entry));

    info = (HXStatisticsDialog*)g_object_get_data(G_OBJECT(toplevel), "info");
    g_return_if_fail(info != NULL);
    
    text = gtk_entry_get_text(entry);

    if(text)
    {
        if(strlen(text) >= source_len + stream_len + 3)
        {
            text += source_len;
            info->current_source = atoi(text);
            
            while(*text && *text != '.')
            {
                text++;
            }

            text += stream_len + 1;

            info->current_stream = atoi(text);
            
            update_statistics(info);
        }
    }    
}

static void
hsd_destroy (GtkWidget* /* widget */,
             HXStatisticsDialog* info)
{
    g_signal_handler_disconnect(G_OBJECT(info->player), info->clip_bandwidth_handler);
    g_signal_handler_disconnect(G_OBJECT(info->player), info->play_handler);

    g_array_free(info->stream_counts_array, TRUE);

    gtk_timeout_remove(info->timer_id);

    glade_xml_destroy (info->xml);

    g_object_unref(info->bandwidth_observer);

    g_free(info);
}

static void
hsd_size_request (GtkWidget *widget,
                  GtkRequisition *request_out)
{
    if(request_out->width > widget->allocation.width)
    {
        /* We're going to have to grow, so grow big  */
        request_out->width = (gint)(1.05 * request_out->width);
    }
    else
    {
        /* Pin us at the currently allocated width */
        request_out->width = widget->allocation.width;
    }
}


GtkDialog*
hxplay_statistics_dialog_new (HXPlayer* player)
{
    GladeXML *xml;
    GtkWidget *dialog;
    gchar *filename;
    HXStatisticsDialog* info;
    gboolean result;
    GtkWidget* bandwidth_graph;
    GValue value;

    memset(&value, 0, sizeof(value));
    
    filename = hxcommon_locate_file("statistics.glade");
    xml = glade_xml_new (filename, NULL, NULL);
    g_free(filename);
    g_return_val_if_fail(xml != NULL, NULL);

    info = g_new0(HXStatisticsDialog, 1);    
    result = get_statistic_dialog_info(xml, player, info);
    g_return_val_if_fail(result, NULL);

    dialog = glade_xml_get_widget (xml, "hxplayer_statistics_dialog");
    g_object_set_data(G_OBJECT(dialog), "info", info);

    bandwidth_graph = glade_xml_get_widget (xml, "hsd_bandwidth_graph");
    
    result = hx_player_get_statistic(player, "ClipBandwidth", &value);
    if(result)
    {
        gint bandwidth;
        bandwidth = g_value_get_int(&value);        
        hx_bandwidth_graph_set_ideal_bandwidth(HX_BANDWIDTH_GRAPH(bandwidth_graph),
                                               bandwidth);
        g_value_unset(&value);        
    }

    
    info->bandwidth_observer = hx_statistics_observer_new(player,
                                                         "CurrentBandwidth");
    update_statistics(info);
    
    info->timer_id = gtk_timeout_add(STATISTICS_UPDATE_INTERVAL,
                                     hsd_update_statistics,
                                     info);
        
    /* Use current clip bandwidth as max/min bandwidth */
    result = hx_player_get_statistic(player, "CurrentBandwidth", &value);
    if(result)
    {
        update_bandwidth(info, &value);
        g_value_unset(&value);
    }

    info->clip_bandwidth_handler =
        g_signal_connect_swapped(G_OBJECT(player),
                                 "clip_bandwidth_changed",
                                 G_CALLBACK(hx_bandwidth_graph_set_ideal_bandwidth),
                                 bandwidth_graph);

    info->play_handler =
        g_signal_connect_swapped(G_OBJECT(player),
                                 "play",
                                 G_CALLBACK(hsd_play),
                                 info);

    g_signal_connect(info->bandwidth_observer,
                     "statistic_modified",
                     G_CALLBACK(hsd_update_bandwidth),
                     info);

    g_signal_connect (G_OBJECT (dialog), "destroy",
                      G_CALLBACK (hsd_destroy),
                      info);

    g_signal_connect (G_OBJECT (dialog), "size-request",
                      G_CALLBACK (hsd_size_request),
                      info);

    return GTK_DIALOG(dialog);
}
