#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

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


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

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

#include "gconfig.h"

#include "gconfig.h"
#include "dvdformat.h"
#include "dvdtools.h"
#include "dvdcopy.h"
#include "dvdbackup.h"
#include "dvd2vob.h"
#include "dvd2avi.h"
#include "uitools.h"
#include "message.h"
#include "avancement.h"
#include "globals.h"
#include "main.h"
#include "mpeg2dec.h"
#include "profile.h"

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

static SelectInfo_t SelInfo;

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

static gboolean RecordAudioSelected(	GtkTreeModel  *model,
					GtkTreePath   *path,
					GtkTreeIter   *iter,
					gpointer       userdata )
{
	gboolean bool;

	gtk_tree_model_get( model, iter, AUDIO_COL1_CHECK, &bool, -1);
	if( bool ) {
		int noPiste;

		gtk_tree_model_get( model, iter, AUDIO_COL8_NO, &noPiste, -1);
		CTEST(fprintf(stderr,"PisteAudio %d selected\n", noPiste ););
		SelInfo.audioMap.audioTracks[noPiste] = 1;
		SelInfo.nbAudio++;
	}
	return( FALSE );
}
/*------------------------------------------------------------------------------
	RECORDSUBSELECTED-
Linux!jef 2006/01/26 20:34:55
------------------------------------------------------------------------------*/

static gboolean RecordSubSelected(	GtkTreeModel  *model,
					GtkTreePath   *path,
					GtkTreeIter   *iter,
					gpointer       userdata )
{
	gboolean bool;

	gtk_tree_model_get( model, iter, SUB_COL1_CHECK, &bool, -1);

	if( bool ) {
		int noPiste;

		gtk_tree_model_get( model, iter, SUB_COL6_NO, &noPiste, -1);
		CTEST(fprintf(stderr,"PisteSub %d selected\n", noPiste ););
		SelInfo.subMap.subTracks[noPiste] = 1;
		SelInfo.nbSub++;
	}
	return( FALSE );
}

/*------------------------------------------------------------------------------
	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;

	item = lookup_widget( forme, "Encoder" );
	g_assert( item );
	if( GTK_WIDGET_SENSITIVE( GTK_WIDGET(item) ) != TRUE )	return;

/* This will only work in single or browse selection mode! */
	item = lookup_widget( forme, "PistesVideo" );
	g_assert( item );
	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(item));
	if( gtk_tree_selection_get_selected(selection, &model, &iter)) {
		gint noPiste;

		gtk_tree_model_get( model, &iter, VIDEO_COL8_NO, &noPiste, -1);
		CTEST(fprintf(stderr,"Piste video %d selected\n", noPiste ););
		SelInfo.noPisteVideo = noPiste;
	}

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

	model = gtk_tree_view_get_model( GTK_TREE_VIEW( item ));
	g_assert( model );
	gtk_tree_model_foreach( GTK_TREE_MODEL(model), 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" );
	g_assert( item );
	model = gtk_tree_view_get_model( GTK_TREE_VIEW( item ));
	g_assert( model );
	gtk_tree_model_foreach( GTK_TREE_MODEL(model), RecordSubSelected, NULL );
	CTEST(fprintf(stderr,"Il y a %d sub tracks\n", SelInfo.nbSub ););
}

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


void
on_proprietes_clicked                  (GtkToolButton   *toolbutton,
                                        gpointer         user_data)
{
	GtkWidget * parent = lookup_widget(GTK_WIDGET(toolbutton), "main" );

	g_assert( parent );
	DialogPropriete( parent, 0 );
	{/* Update media */
		char title[512];
		int dvdFormat = ConfigGetInt( KEY_MEDIA, DVD5 );
		Profile_t * p = GetProfile( dvdFormat );
		CTEST(fprintf(stderr,"%s: dvdFormat=%d p=%p\n", __FUNCTION__, dvdFormat, p ););
		if( !p ) {
			dvdFormat = DVD5;
			p = GetProfile( dvdFormat );
			g_assert( p );
		}
		if( p->profileFlags & PROFILE_AVAIL_F ) {
			SetFormat( dvdFormat );
		}
		else {
			dvdFormat = DVD5;
			SetFormat( dvdFormat );
			p = GetProfile( dvdFormat );
			g_assert( p );
		}
		sprintf( title, "%s : %s",  _("DVD 9 to 5"), p->libel );
		gtk_window_set_title( GTK_WINDOW(parent), title );
	}
	DeviceChecking( parent );
	GetSelected( parent );
	if( SelInfo.noPisteVideo != -1 ) {
		UpdDefFactor( parent, SelInfo.noPisteVideo, &SelInfo.audioMap, &SelInfo.subMap );
	}
}


void
on_ViewPiste_clicked                   (GtkToolButton   *toolbutton,
                                        gpointer         user_data)
{
	GtkWidget * forme = lookup_widget(GTK_WIDGET(toolbutton), "main" );

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

gboolean
on_PistesVideo_button_press_event      (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{

  return FALSE;
}


gboolean
on_PistesAudio_button_press_event      (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{

  return FALSE;
}


gboolean
on_SousTitres_button_press_event       (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{

  return FALSE;
}

void
on_cfgsave_clicked                     (GtkObject       *object,
                                        gpointer         user_data)
{
	SaveConfig( GTK_WIDGET(object) );
	if( VerifConfig( GTK_WIDGET( object ) ) != -1 ) {
		GtkWidget * propriete;

		propriete = lookup_widget(GTK_WIDGET(object), "propriete" );
		g_assert( propriete );
		gtk_widget_destroy( propriete );
	}
}


void
on_cfgiso_destroy                      (GtkObject       *object,
                                        gpointer         user_data)
{

}


void
on_propriete_destroy                   (GtkObject       *object,
                                        gpointer         user_data)
{
	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();

		gtk_file_filter_set_name( fi, _("Fichiers ISO") );
		gtk_file_filter_add_pattern( fi, "*.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));
			strcpy( Device, filename );
			DeviceSpecifiedF = 1;
			g_free (filename);
		}
		gtk_widget_destroy( fc );
	}
}


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)) {
		gint noPiste;

		gtk_tree_model_get( model, &iter, VIDEO_COL8_NO, &noPiste, -1);

		ScanPiste( widget, noPiste );
	}
	else {
//		g_print ("no row selected.\n");
	}
//	fprintf(stderr,"Piste video button press!\n");


  return FALSE;
}


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

	g_assert( forme );
	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), "main" );

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

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

	return( FALSE );
}

void
on_Encoder_clicked                     (GtkToolButton   *toolbutton,
                                        gpointer         user_data)
{
	GtkWidget * forme = lookup_widget(GTK_WIDGET(toolbutton), "main" );
	GtkWidget * item;
	double facteur;
	double pct;
	int res;
	Profile_t * p;

	g_assert( forme );
	GetSelected( forme );

	item = lookup_widget(GTK_WIDGET(toolbutton), "Qualite" );
	g_assert( item );
	pct = gtk_range_get_value( GTK_RANGE(item) );
	if( !pct )	pct = 1.0;

	facteur = (100.0 / pct );

	if( SelInfo.noPisteVideo == -1 ) {
		MessageBoxError( _("Veuillez selectionner une piste video") );
		return;
	}
	if( ! SelInfo.nbAudio == -1 ) {
		MessageBoxError( _("Veuillez selectionner une piste audio") );
		return;
	}
	p = GetProfile( GetFormat() );
	g_assert( p );

	CreateDirectorys();
	if( p->profileFlags & PROFILE_AVI_F ) {
		res = DvdToAvi(		forme,
					SelInfo.noPisteVideo,
					&SelInfo.audioMap,
					&SelInfo.subMap,
					GetFormat() );
	}
	else {
		if( facteur < 0 ) {
			MessageBoxError( _("Veuillez lancer un calcul de qualit‚") );
			return;
		}
		if( ConfigGetInt( KEY_USEMENU, 0 ) ) {
			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 ) {
		EncodageFini();
//!!		gtk_widget_destroy( forme );
	}
	else {
		MessageBoxError( _("Erreur de conversion ........") );
	}
}


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


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


void
on_Evaluer_clicked                     (GtkToolButton   *toolbutton,
                                        gpointer         user_data)
{
	GtkWidget * forme = lookup_widget(GTK_WIDGET(toolbutton), "main" );
	GtkWidget * item;
	double facteur;
	double pct;
	int res;
	int menuF = ConfigGetInt( KEY_USEMENU, 0 );

	g_assert( forme );

	GetSelected( forme );

	if( SelInfo.noPisteVideo == -1 ) {
		MessageBoxError( _("Veuillez selectionner une piste video") );
		return;
	}
	if( ! SelInfo.nbAudio == -1 ) {
		MessageBoxError( _("Veuillez selectionner une piste audio") );
		return;
	}

	res = CpuBackupQuality(	forme,
				SelInfo.noPisteVideo,
				&SelInfo.audioMap,
				&SelInfo.subMap,
				menuF,
				&facteur );
	item = lookup_widget( forme, "Qualite" );
	g_assert( item );

	pct = (1.0 / facteur ) * 100.0;
// fprintf(stderr,"dFactor=%f qualite=%f\n", dFactor, pct );
	gtk_range_set_value( GTK_RANGE( item ), pct );

	gtk_widget_show( item );
}


void
on_quitter_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{

}


void
on_rafraichir_clicked                  (GtkButton       *button,
                                        gpointer         user_data)
{

}


void
on_lecture_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{
	VisuDvdStruct( TargetDir );
}


void
on_revenir_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{
	Phase2 = PHASE2_ARRIERE;
}


void
on_avancer_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{
	Phase2 = PHASE2_AVANCER;
}

void
on_arreter_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{

}


void
on_fermer_clicked                      (GtkButton       *button,
                                        gpointer         user_data)
{

}


void
on_cfgdev_changed                      (GtkComboBox     *combobox,
                                        gpointer         user_data)
{
	gchar * value;

	value = gtk_combo_box_get_active_text( combobox );
	if( value ) 	gtk_entry_set_text( GTK_ENTRY (GTK_BIN(combobox)->child), value );
}


void
on_cfgvisu_changed                     (GtkComboBox     *combobox,
                                        gpointer         user_data)
{
	gchar * value;

	value = gtk_combo_box_get_active_text( combobox );
	if( value ) 	gtk_entry_set_text( GTK_ENTRY (GTK_BIN(combobox)->child), value );
}


static void
handle_url (GtkAboutDialog *about, const char *link, gpointer data)
{
	gchar *command[] = {"gnome-open", NULL, NULL};

	command[1] = g_strdup (link);
	g_spawn_async(NULL, command, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL);
	g_free (command[1]);
}

void
on_About_clicked                       (GtkToolButton   *toolbutton,
                                        gpointer         user_data)
{
	GtkWidget * msg;

	msg = create_about();

	gtk_about_dialog_set_url_hook (handle_url, NULL, NULL);
	gtk_dialog_run( GTK_DIALOG( msg ) );
	gtk_widget_destroy( GTK_WIDGET( msg ) );
}

gboolean
on_Dvd95_delete                        (GtkWidget       *widget,
                                        GdkEvent        *event,
                                        gpointer         user_data)
{
	ConfigRecordSizePosMain( MainDlg );
	gtk_main_quit();
	return TRUE;
}


void
on_visumpeg_toggled                    (GtkToggleButton *togglebutton,
                                        gpointer         user_data)
{
	if( gtk_toggle_button_get_active( togglebutton ) == TRUE ) {
// fprintf(stderr,"MPEG2 DECODER: Enabled\n");
		Mpeg2SetState( 1 );
	}
	else {
// fprintf(stderr,"MPEG2 DECODER: Disabled\n");
		Mpeg2SetState( 0 );
	}
}

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

	g_assert( parent );
	DialogPropriete( parent, 1 );
}

