#!/usr/bin/perl 

use warnings;
use strict;

my $N;
do {
    $N = entry ( "Introduzca N", "Introduzca N numérico:", 1);
    chomp ($N);
# print "$N\n";
} until ($N+0 eq $N);

my $date = calendar();
info ("La fecha introducida es $date.");

my $file = file_selection ( "Seleccione el fichero a abrir:" );
chomp ($file);
# print "$file\n";

my $value = scale(); 

info( "Se ha introducido $N como dato, $value como parámetro y $file como fichero." ); 

my @list = 0..10; # warning!
progress ( "Se ha completado el 100 %", "# Progreso:" , \@list );  


my $bool = question("¿Le gusta zenity?");
if ($bool==0) {
    print "Zenity is good\n";
}else{
    print "Zenity could be improved\n";
}

exit 1;


sub question {
    my ($text) = @_;
    my $r = `zenity --question --text="$text"`;
    return $?;
}

sub calendar {
    my $d;
    $d = `zenity --calendar`;
    chomp $d;
    return $d;
}

sub entry {
    my ($title, $text, $default) = @_;
    my $r= `zenity --entry --title="$title" --text="$text" --entry-text "$default"`;
    return $?;
}

sub file_selection {
    my ($text) = @_;
    my $file = `zenity --file-selection --title="$text"`;
    return $file;   
# case ($?) in
#      0)
#  echo "\"$FILE\" seleccionado."
#  ;;
# 1)
#  echo "No ha seleccionado ningún archivo."
#  ;;
# -1)
#  echo "Ha ocurrido un error inesperado."
#  ;;
# esac
}  

sub info {
    my ($text) = @_;
    `zenity --info --text="$text"`
}
  
sub progress {
    my ($title, $text, $percentage) = @_;
    open ZEN, "|-", "zenity --progress title=\"$title\" text=\"$text\" percentage=0" or 
      die "Cannot open zen";
    select((select(ZEN),$|=1)[0]);
    for my $i (@$percentage) {
	print ZEN "$i\n";
	if ( $? == -1 ) {
	    error( "¡Cancelado!" );
	    exit -1;
	}
	sleep 1;
    }
    close ZEN;
}

sub error {
    my ($text) = @_; 
    `zenity --error text="$text"`;
}
      
sub scale {
    my $v = shift // 50;
    my $value =`zenity --scale --text="Select percent value" --value="$v"`; 
    if ( $? == 1 ) {
	$value = $v;
	error ( "No se ha alterado el valor.");
    }
    return $value/100;
}
