#!/usr/bin/perl
use strict;
use Gtk2 -init;
use Gtk2::GladeXML;
use UI::Dialog;
use UI::Dialog::Backend::Zenity;
use Switch;

## Declarando Variables

my($programa, $ventana_principal, $fondo_path, $boton_salir, $path_images, $pid_programa, $etiqueta_numero_de_segundos, $numero_de_segundos, $label_estado, $ventana_acerca_de, $acerca_de, $ventana_preferencias, $filechooserbutton, $file_chosse);

my(@estado, $home_directory, $parte_del_path, $path, $path_pid, $nombre_ultimo_fondo);

## De la ventana de preferencias
my($deja_ultimo_fondo_widget, $tipo_de_cambio_widget, $tipo_de_cambio, $cambio_definitivo);
my $deja_ultimo_fondo = 1;

&basura;

## Cargando todo el UI::Dialog
my $ventanas_dialogs = new UI::Dialog::Backend::Zenity(title => "Gbackground",
						       height => 45, width => 50, 
						       listheight => 5,
						       order => [ 'zenity', 'xdialog', 'gdialog']
						       );

# Para cuando voy a empaquetar

if (-e 'glade/gbackground.glade'){
	$programa = Gtk2::GladeXML->new('glade/gbackground.glade');
} else {
	$programa = Gtk2::GladeXML->new('/usr/share/gbackground/gbackground.glade');
}

# Cargando Ventanas

&cargar_widgets;

# Signals
$programa->signal_autoconnect_from_package('main');

## Verificando el estado del programa

&verificando_estado;

Gtk2->main;

## Funciones ##
sub basura {
	@estado = ("<span foreground=\"blue\">Running</span>", "<span foreground=\"red\">Stoped</span>");
	$home_directory = $ENV{HOME};
	$path_pid = $home_directory . "/.gbackground" . "/gbackground.pid";
	$cambio_definitivo = 'stretched';
}
sub cargar_widgets {
	$ventana_principal = $programa->get_widget('ventana_principal');
	$ventana_preferencias = $programa->get_widget('ventana_preferencias');
	$etiqueta_numero_de_segundos = $programa->get_widget('etiqueta_numero_de_segundos');
	$label_estado = $programa->get_widget('label_estado');
	$ventana_acerca_de = $programa->get_widget('Acerca_de');
	$acerca_de = $programa->get_widget('acerca_de');
	$deja_ultimo_fondo_widget = $programa->get_widget('ventana_preferencias_fondo');
	$tipo_de_cambio_widget = $programa->get_widget('combobox1');
	$filechooserbutton = $programa->get_widget('filechooserbutton');
	$filechooserbutton->set_current_folder_uri("/usr/share/images/desktop-base/");
}

sub verificando_estado {
	if(-e $path_pid){
	        $label_estado->set_markup("@estado[0]");
	}else{
	        $label_estado->set_markup("@estado[1]");
	}
}

sub on_boton_iniciar_clicked {
	$path_images = $filechooserbutton->get_filename;
	$nombre_ultimo_fondo = `gconftool-2 --get /desktop/gnome/background/picture_filename`;
	$nombre_ultimo_fondo =~ s/\s/\\ /g;
	if(-e "$path_pid"){
		$ventanas_dialogs->error(title => 'Error!!', text => 'Gbackground <b>is already</b> working');
		}
	else{
		if(-e $path_images){
			$numero_de_segundos = $etiqueta_numero_de_segundos->get_text();
			$path_images =~ s/\s/\\ /g;
			if(-e './gbackgroundD'){
				system("perl ./gbackgroundD \"$path_images\" $numero_de_segundos $cambio_definitivo \&");
			} else {
				system("perl /usr/share/gbackground/gbackgroundD \"$path_images\" $numero_de_segundos $cambio_definitivo \&");
			}
			
			sleep 1; # Esto es por que muchas veces tarda en crear el gbackground.pid
			$label_estado->set_markup("@estado[0]") if(-e "$path_pid");
			$ventanas_dialogs->msgbox(title => "Daemon Gbackground", text => 'Gbackground has started <b>successfully</b>');	
		}
		else{
			$ventanas_dialogs->error(title => "Error, dir doesn't exist", text => 'The directory that you introduced <b>is not valid</b>, please verify it and try again');	
		}
	}
}
sub on_boton_parar_clicked {
	if(-e "$path_pid"){
		open(ARCHIVO_PID, "$path_pid");
		while(<ARCHIVO_PID>){
			$pid_programa = $_;
		}
		system("kill -9 $pid_programa");
		system("rm -f $path_pid");
		if($deja_ultimo_fondo == 1){
				system("gconftool-2 -t str -s /desktop/gnome/background/picture_filename $nombre_ultimo_fondo");
		}
		$ventanas_dialogs->msgbox(title => "Daemon Gbackground", text => 'Gbackground has been <b>stopped</b> successfully'); 
		$ventanas_dialogs->error(title => 'Error!!', text => 'Error, it was not possible to stop Gbackground. Probably because it <b>is not</b> running') if(-e "$path_pid");
	}else{
		$ventanas_dialogs->error(title => 'Error!!', text => 'Gbackground <b>is not</b> running');	
	}
	&verificando_estado;
}

sub on_ventana_preferencias_boton_aceptar_clicked {
	$deja_ultimo_fondo = $deja_ultimo_fondo_widget->get_active;
	$cambio_definitivo = $tipo_de_cambio_widget->get_active_text();
	$ventana_preferencias->hide;
}

## Para que cuando cierren las ventanas y las vuelvan a abrir no desaparezcan
sub on_acerca_de_delete_event {
    my $w = shift;
    $w->hide;
    1; 
}

sub on_ventana_preferencias_delete_event {
    my $w = shift;
    $w->hide;
    1; 
}

sub on_ventana_principal_delete_event {Gtk2->main_quit;}
sub on_boton_salir_clicked {Gtk2->main_quit;}
sub on_quit1_activate {Gtk2->main_quit;}
sub on_salir1_activate {Gtk2->main_quit;}
sub on_acerca_de1_activate {$acerca_de->present;}
sub on_preferencias1_activate {
	my $valor = $tipo_de_cambio_widget->set_active("1");
	$ventana_preferencias->show_all;
}
sub on_ventana_preferencias_boton_cancelar_clicked {$ventana_preferencias->hide;}
sub on_acerca_de_close {$acerca_de->hide;}
sub on_acerca_de_response { $acerca_de->hide;}
