#include <gtk/gtk.h>

#include "config.h"

#ifdef MAEMO_PLATFORM
#include "hildon-widgets/hildon-program.h"
#include "hildon-widgets/hildon-window.h"
#endif

#include <gmyth/gmyth_recorder.h>
#include <gmyth/gmyth_backendinfo.h>
#include <gmyth/gmyth_tvchain.h>
#include <gmyth/gmyth_remote_util.h>

#include "mmyth_ui.h"
#include "mmyth_tvplayer.h"

static void
cb_destroy (GtkWidget * widget, gpointer data)
{
    MMythUi *mmyth_ui = (MMythUi *) data;

    if (mmyth_ui->tvplayer != NULL) {
    	if (mmyth_tvplayer_is_playing (mmyth_ui->tvplayer) )
    		mmyth_tvplayer_stop_playing (mmyth_ui->tvplayer);
    }

	mmyth_ui_finalize (mmyth_ui);
	
    gtk_main_quit ();
}

#ifdef NDEBUG
static void
debug_error_func( const gchar*log_domain, GLogLevelFlags log_level, const gchar *message,
	gpointer user_data )

{
	/* leave this with NO print out messages, once you need to disable debug messages! */
	//g_print ( "[%s] DEBUG messages disabled!\n", __FUNCTION__ );
}
#endif

gint
main (gint argc, gchar * argv[])
{
    GtkWidget *window;
    MMythUi *mmyth_ui;
#ifdef MAEMO_PLATFORM
    HildonProgram *program = NULL;
#endif

    /* init threads */
    g_thread_init (NULL);

    /* Initializes GTK */
    gtk_init (&argc, &argv);
    gst_init (&argc, &argv);
#ifdef NDEBUG
 g_log_set_default_handler( debug_error_func, NULL );
#endif

    /* Init libmmyth context */
	/* TODO */
#ifndef MAEMO_PLATFORM
    /* create the main window */
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_widget_set_size_request (window, MAIN_WINDOW_WIDTH, MAIN_WINDOW_HEIGHT);
    gtk_window_set_title (GTK_WINDOW (window), "Mythtv Frontend");
#else
    /* Creating Hildonized main view */
    program = HILDON_PROGRAM(hildon_program_get_instance());
    window = hildon_window_new();

    //g_signal_connect(G_OBJECT(window), "delete_event", gtk_main_quit, NULL);

    hildon_program_add_window(program, HILDON_WINDOW (window));
    g_set_application_name("Maemo Mythtv"); 
#endif
   
    /* Initializes MMyth Widgets */
#ifdef MAEMO_PLATFORM
    mmyth_ui = mmyth_ui_initialize (program, window);
#else    
    mmyth_ui = mmyth_ui_initialize (window);
#endif
    
    //mmyth_ui->loop = g_main_loop_new (NULL, FALSE);

    /* Connect destroy signal handling */
    g_signal_connect (window, "destroy", G_CALLBACK (cb_destroy), mmyth_ui);

    /* Shows main window and start gtk loop */
    gtk_widget_show (window);

    gtk_main ();

    return 0;
}