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

#include <ctype.h>
#include <gnome.h>

#define CTEST( x )		/****/

#include "callbacks.h"
#include "interface.h"
#include "support.h"

#include "gconfig.h"
#include "dvdformat.h"
#include "dvdtools.h"
#include "dvdcopy.h"
#include "dvdbackup.h"
#include "dvd2vob.h"
#include "uitools.h"
#include "message.h"
#include "avancement.h"

#define __NEED_GLOBALS__
#include "globals.h"

typedef struct
{
	int noPisteVideo;
	AudioMap_t audioMap;
	int nbAudio;
	int firstAudio;
	SubMap_t subMap;
	int nbSub;
	int firstSub;
	int menuF;
} SelectInfo_t;

static SelectInfo_t SelInfo;


void
on_Quitter_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{
	CTEST(fprintf(stderr,"%s-%d\n", __FILE__,__LINE__););
	gtk_main_quit();
}


void
on_button2_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget * parent = lookup_widget(GTK_WIDGET(button), "Dvd95" );

	DialogPropriete( parent );
}

/* Sortie de l'ecran propriete */
void
on_button4_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget * propriete;

	propriete = lookup_widget(GTK_WIDGET(button), "propriete" );
	if( propriete ) {
		gtk_widget_destroy( propriete );
	}
}


void
on_verifconfig_clicked                 (GtkButton       *button,
                                        gpointer         user_data)
{
	VerifConfig( GTK_WIDGET( button ) );
}
/*------------------------------------------------------------------------------
	SETRADIOS-
Linux!jef 2006/02/27 22:54:56
------------------------------------------------------------------------------*/

static void SetRadios( GtkWidget *  forme )
{
	char * useMenu = ConfigGetString( KEY_USEMENU, "1" );
	char * viewResult = ConfigGetString( KEY_PREVIEW, "0" );
	char * doIso = ConfigGetString( KEY_DOISO, "0" );
	char * qualDyn = ConfigGetString( KEY_QUALDYN, "0" );
	char * graver = ConfigGetString( KEY_GRAVER, "0" );

	ToggleSet( forme, "UseMenu", *useMenu == '1' ? 1 : 0 );
	ToggleSet( forme, "ViewResult", *viewResult == '1' ? 1 : 0 );
	ToggleSet( forme, "DoIso", *doIso == '1' ? 1 : 0 );
	ToggleSet( forme, "dynqual", *qualDyn == '1' ? 1 : 0 );
	ToggleSet( forme, "graver", *graver == '1' ? 1 : 0 );
}

/*------------------------------------------------------------------------------
	UPDATERADIOS-
Linux!jef 2006/02/27 22:56:30
------------------------------------------------------------------------------*/

static void UpdateRadios( GtkWidget *  forme )
{
	if( IsToggleSet( forme, "UseMenu" ) )
		SetConfigString( KEY_USEMENU, "1" );
	else
		SetConfigString( KEY_USEMENU, "0" );
	if( IsToggleSet( forme, "ViewResult" ) )
		SetConfigString( KEY_PREVIEW, "1" );
	else
		SetConfigString( KEY_PREVIEW, "0" );
	if( IsToggleSet( forme, "DoIso" ) )
		SetConfigString( KEY_DOISO, "1" );
	else
		SetConfigString( KEY_DOISO, "0" );
	if( IsToggleSet( forme, "dynqual" ) )
		SetConfigString( KEY_QUALDYN, "1" );
	else
		SetConfigString( KEY_QUALDYN, "0" );
	if( IsToggleSet( forme, "graver" ) )
		SetConfigString( KEY_GRAVER, "1" );
	else
		SetConfigString( KEY_GRAVER, "0" );
}


void
on_DoScan_clicked                      (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget * Scanning;
	GtkWidget * parent = lookup_widget(GTK_WIDGET(button), "Dvd95" );
	GtkWidget * old;
	char * device = ConfigGetString( KEY_DEVICE, "/dev/dvd" );
	int ret;

	ret = IsDvdLoaded( device );
	switch( ret ) {
		case -1 :
			MessageBox("Le peripherique est invalide !");
			return;
		case 0 :
			MessageBox("Veuillez inserer un dvd !");
			return;
	}
	InitTrace();
	SetFormat( DVD5 );
	Scanning = create_Scanning();
	gtk_window_set_transient_for( GTK_WINDOW(Scanning), GTK_WINDOW(parent) );
	old = AlerteSetParent( Scanning );
	SetRadios( Scanning );
	gtk_widget_show_now( Scanning );
	while( gtk_events_pending() )	gtk_main_iteration();
	ScanDvd( Scanning );
	CTEST(fprintf(stderr,"%s-%d\n", __FILE__,__LINE__););
	gtk_main();
	CTEST(fprintf(stderr,"%s-%d\n", __FILE__,__LINE__););
	AlerteSetParent( old );
}
/*------------------------------------------------------------------------------
	DESTROYFFORMSCANNING-
Linux!jef 2006/03/27 22:08:26
------------------------------------------------------------------------------*/

static void DestroyFormScanning( GtkWidget * widget )
{
	GtkWidget * Scanning;

	CTEST(fprintf(stderr,"%s-%d\n", __FILE__,__LINE__););
	Scanning = lookup_widget( widget, "Scanning" );
	if( Scanning ) {
		CTEST(fprintf(stderr,"%s-%d\n", __FILE__,__LINE__););
		UpdateRadios( Scanning );
		gtk_widget_destroy( Scanning );
	}
}

void
on_scanQuit_clicked                    (GtkButton       *button,
                                        gpointer         user_data)
{
	CTEST(fprintf(stderr,"%s-%d\n", __FILE__,__LINE__););
	DestroyFormScanning( GTK_WIDGET(button ));
}


void
on_cfgsave_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{
	SaveConfig( GTK_WIDGET(button) );
}

gboolean
on_PistesVideo_button_press_event      (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{
	return( FALSE );
}


gboolean
on_PistesVideo_button_release_event    (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{
	GtkTreeSelection *selection;
	GtkTreeModel     *model;
	GtkTreeIter       iter;

/* This will only work in single or browse selection mode! */

	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget));
	if( gtk_tree_selection_get_selected(selection, &model, &iter)) {
		gchar *name;
		int noPiste;
		char * p;
		gtk_tree_model_get (model, &iter, 0, &name, -1);

//		g_print ("selected row is: %s\n", name);

		p = name + strlen( _("Piste") );
		while( *p == ' ' )	p++;
		noPiste = atoi( p );
		g_free(name);
		ScanPiste( widget, noPiste - 1 ); /* Zero based */
	}
	else {
//		g_print ("no row selected.\n");
	}
//	fprintf(stderr,"Piste video button press!\n");

  return FALSE;
}

/*------------------------------------------------------------------------------
	RECORDAUDIOSELECTED-
Linux!jef 2006/01/26 20:34:55
------------------------------------------------------------------------------*/

static void RecordAudioSelected(	GtkTreeModel  *model,
					GtkTreePath   *path,
					GtkTreeIter   *iter,
					gpointer       userdata )
{
	gchar *name;
	char * p;

	gtk_tree_model_get( model, iter, 0, &name, -1);
	p = name;
	while( *p && !isdigit(*p))	p++;
	if( *p ) {
		int track;

		track = atoi( p ) - 1; /* Zero based */

		CTEST(fprintf(stderr,"PisteAudio %d selected\n", track ););
		SelInfo.audioMap.audioTracks[track] = 1;
		SelInfo.nbAudio++;
		if( !SelInfo.firstAudio )	SelInfo.firstAudio = track;
	}
	g_free(name);
}
/*------------------------------------------------------------------------------
	RECORDSUBSELECTED-
Linux!jef 2006/01/26 20:34:55
------------------------------------------------------------------------------*/

static void RecordSubSelected(	GtkTreeModel  *model,
					GtkTreePath   *path,
					GtkTreeIter   *iter,
					gpointer       userdata )
{
	gchar *name;
	char * p;

	gtk_tree_model_get( model, iter, 0, &name, -1);
	p = name;
	while( *p && !isdigit(*p))	p++;
	if( *p ) {
		int track;

		track = atoi( p ) - 1; /* Zero based */

		CTEST(fprintf(stderr,"PisteSub %d selected\n", track ););
		SelInfo.subMap.subTracks[track] = 1;
		SelInfo.nbSub++;
		if( !SelInfo.firstSub )	SelInfo.firstSub = track;
	}
	g_free(name);
}

/*------------------------------------------------------------------------------
	GETSELECTED-
Linux!jef 2005/12/18 19:46:04
------------------------------------------------------------------------------*/

static void GetSelected( GtkWidget * forme )
{
	GtkWidget * item;
	GtkTreeSelection *selection;
	GtkTreeModel     *model;
	GtkTreeIter       iter;

	memset( &SelInfo, 0, sizeof( SelInfo ));
	SelInfo.noPisteVideo = -1;

/* This will only work in single or browse selection mode! */
	item = lookup_widget( forme, "PistesVideo" );
	if( !item )	return;
	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(item));
	if( gtk_tree_selection_get_selected(selection, &model, &iter)) {
		gchar *name;
		char * p;

		gtk_tree_model_get (model, &iter, 0, &name, -1);
		p = name;
		while( *p && !isdigit(*p))	p++;
		if( *p ) {
			SelInfo.noPisteVideo = atoi( p ) - 1; /* Zero based */
		}
		g_free(name);
	}

/* This will only work in single or browse selection mode! */
	item = lookup_widget( forme, "PistesAudio" );
	if( !item )	return;
	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(item));

	gtk_tree_selection_selected_foreach(selection, RecordAudioSelected, NULL);
	CTEST(fprintf(stderr,"Il y a %d audio tracks\n", SelInfo.nbAudio ););

/* This will only work in single or browse selection mode! */
	item = lookup_widget( forme, "SousTitres" );
	if( !item )	return;
	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(item));
	gtk_tree_selection_selected_foreach(selection, RecordSubSelected, NULL);

	CTEST(fprintf(stderr,"Il y a %d sub tracks\n", SelInfo.nbSub ););

	SelInfo.menuF = IsToggleSet( forme, "UseMenu" );
}


void
on_CalculQualite_clicked               (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget * forme = lookup_widget(GTK_WIDGET(button), "Scanning" );
	GtkWidget * item;
	double facteur;
	char string[100];
	double pct;
	int res;

	GetSelected( forme );

	if( SelInfo.noPisteVideo == -1 ) {
		Alerte(0,_("Veuillez selectionner une piste video") );
		return;
	}
	if( !SelInfo.nbAudio ) {
		Alerte(0,_("Veuillez selectionner une piste audio") );
		return;
	}
	res = CpuBackupQuality(	forme,
				SelInfo.noPisteVideo,
				&SelInfo.audioMap,
				&SelInfo.subMap,
				SelInfo.menuF,
				&facteur );
	item = lookup_widget( forme, "Qualite" );
	sprintf( string,"%.4f", facteur );
	gtk_entry_set_text( GTK_ENTRY(item), string );
	gtk_widget_show( item );

	item = lookup_widget( forme, "qpct" );
//	pct = (1 - (facteur - 1)) * 100;
	pct = (1.0 / facteur) * 100.0;
	sprintf( string,"%.2f%%", pct );
	gtk_label_set_text( GTK_LABEL(item), string );
	gtk_widget_show_now( item );
}


void
on_avCancel_clicked                    (GtkButton       *button,
                                        gpointer         user_data)
{
	UserStopF = 1;
}


void
on_Encoder_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget * forme = lookup_widget(GTK_WIDGET(button), "Scanning" );
	GtkWidget * item;
	double facteur;
	const gchar * text;
	int res;

	GetSelected( forme );
	if( SelInfo.noPisteVideo == -1 ) {
		Alerte(0,_("Veuillez selectionner une piste video") );
		return;
	}
	if( ! SelInfo.nbAudio == -1 ) {
		Alerte(0,_("Veuillez selectionner une piste audio") );
		return;
	}

	item = lookup_widget( forme, "Qualite" );
	text = gtk_entry_get_text( GTK_ENTRY(item) );

	facteur = atof( text );
	if( facteur < 0 ) {
		Alerte(0,_("Veuillez lancer un calcul de qualit‚") );
		return;
	}
	if( SelInfo.menuF ) {
		res = BackupDvd(	forme,
					SelInfo.noPisteVideo,
					&SelInfo.audioMap,
					&SelInfo.subMap,
					facteur );
	}
	else {
		res = CopyDvd(		forme,
					SelInfo.noPisteVideo,
					&SelInfo.audioMap,
					&SelInfo.subMap,
					facteur );
	}
	DBG('c',{char timeStr[100]; TotalTime( timeStr ); fprintf(stderr,"Temps de traitement: %s\n", timeStr );});
	if( res != -1 ) {
		Alerte(0,_("Fin de conversion reussie ........") );
		DestroyFormScanning( GTK_WIDGET(button ));
	}
	else {
		Alerte(0,_("Erreur de conversion ........") );
	}
}


gboolean
on_PistesAudio_button_release_event    (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{
	GtkWidget * forme = lookup_widget(GTK_WIDGET(widget), "Scanning" );

	GetSelected( forme );
	if( SelInfo.noPisteVideo == -1 )	return( FALSE );

	UpdDefFactor( forme, SelInfo.noPisteVideo, &SelInfo.audioMap, &SelInfo.subMap );

	return( FALSE );
}


gboolean
on_SousTitres_button_release_event     (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{
	GtkWidget * forme = lookup_widget(GTK_WIDGET(widget), "Scanning" );

	GetSelected( forme );
	if( SelInfo.noPisteVideo == -1 ) return( FALSE );

	UpdDefFactor( forme, SelInfo.noPisteVideo, &SelInfo.audioMap, &SelInfo.subMap );

	return( FALSE );
}


void
on_ViewPiste_clicked                   (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget * forme = lookup_widget(GTK_WIDGET(button), "Scanning" );

	GetSelected( forme );
	if( SelInfo.noPisteVideo == -1 ) {
		Alerte(0,_("Veuillez selectionner une piste video") );
		return;
	}
	VisuDvdPiste( SelInfo.noPisteVideo );
}

void
on_UseMenu_toggled                     (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
	GtkWidget * forme = lookup_widget(GTK_WIDGET(togglebutton), "Scanning" );
	GtkWidget * item;

	item = lookup_widget(forme, "PistesAudio" );
	if( IsToggleSet( forme, "UseMenu"))
		gtk_tree_selection_set_mode(gtk_tree_view_get_selection(GTK_TREE_VIEW(item)), GTK_SELECTION_MULTIPLE );
	else
		gtk_tree_selection_set_mode(gtk_tree_view_get_selection(GTK_TREE_VIEW(item)), GTK_SELECTION_SINGLE );


	GetSelected( forme );
	if( SelInfo.noPisteVideo == -1 )	return;
	UpdDefFactor( forme, SelInfo.noPisteVideo, &SelInfo.audioMap, &SelInfo.subMap );
}


void
on_ToDvd9_clicked                      (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget * Scanning;
	GtkWidget * parent = lookup_widget(GTK_WIDGET(button), "Dvd95" );
	GtkWidget * old;
	char * device = ConfigGetString( KEY_DEVICE, "/dev/dvd" );
	int ret;

	ret = IsDvdLoaded( device );
	switch( ret ) {
		case -1 :
			MessageBox("Le peripherique est invalide !");
			return;
		case 0 :
			MessageBox("Veuillez inserer un dvd !");
			return;
	}
	InitTrace();
	SetFormat( DVD9 );
	Scanning = create_Scanning();
	gtk_window_set_transient_for( GTK_WINDOW(Scanning), GTK_WINDOW(parent) );
	old = AlerteSetParent( Scanning );
	SetRadios( Scanning );
	gtk_widget_show_now( Scanning );
	while( gtk_events_pending() )	gtk_main_iteration();
	ScanDvd( Scanning );
	gtk_main();
	AlerteSetParent( old );
	UpdateRadios( Scanning );
	gtk_widget_destroy( Scanning );
}

void
on_Pause_clicked                       (GtkButton       *button,
                                        gpointer         user_data)
{
	if( UserPauseF )
		UserPauseF = 0;
	else
		UserPauseF = 1;
}

void
on_Dvd95_destroy                       (GtkObject       *object,
                                        gpointer         user_data)
{
	gtk_main_quit();
}


void
on_propriete_destroy                   (GtkObject       *object,
                                        gpointer         user_data)
{
	CTEST(fprintf(stderr,"%s:\n", __FUNCTION__ ););
	gtk_main_quit();
}


void
on_Scanning_destroy                    (GtkObject       *object,
                                        gpointer         user_data)
{
	CTEST(fprintf(stderr,"%s:\n", __FUNCTION__ ););
	gtk_main_quit();
}


void
on_choixiso_clicked                    (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget * fc;

	fc = create_ChoixFichier();
	if( fc ) {
		GtkFileFilter * fi =  gtk_file_filter_new();
		GtkWidget * item;

		gtk_file_filter_set_name( fi, _("Fichiers ISO") );
		gtk_file_filter_add_pattern( fi, "*.iso" );
		gtk_file_chooser_add_filter( GTK_FILE_CHOOSER(fc), fi );

		if( gtk_dialog_run (GTK_DIALOG(fc)) == GTK_RESPONSE_OK) {
			char *filename;

			filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER(fc));

			item = lookup_widget( GTK_WIDGET(button), "cfgdev" );
			g_assert( item );
			gtk_entry_set_text( GTK_ENTRY (GTK_BIN (item)->child), filename );
			g_free (filename);
		}
		gtk_widget_destroy( fc );
	}

}

