#!/usr/bin/perl -w
# Fet per David Alcobero Pinyot
# 26-09-08
#
use Gtk2::TrayIcon;
use Gtk2::GladeXML;
use Gtk2 -init;
use Crypt::Lite;
use threads;
#use Gtk2 qw(-threads-init -init);
use Glib qw(TRUE FALSE); 
Glib::Object->set_threadsafe (TRUE); # aixi no peta al sortir (es necessita pels threads)
use strict;
use warnings;

####
my $dir='/home/anguila/Projectes/cvNews';
##
my $logo="$dir/uab.png";
my $logo_off="$dir/uab_off.png";
my $programa = Gtk2::GladeXML->new("$dir/cvnews.glade");
my $crypt = Crypt::Lite->new( debug => 0,encoding => 'hex8' );
my $seek=(getpwuid($<))."cvnews";
my $wait_time_error=20;

my $pic = Gtk2::Image->new_from_file($logo);
my $eventbox = Gtk2::EventBox->new;
$eventbox->add($pic);
my $icon= Gtk2::TrayIcon->new('trayicon');

$icon->add($eventbox);
$icon->signal_connect ('button-release-event'=> \&click);

my $tooltip = Gtk2::Tooltips->new;
$tooltip->set_tip($icon, "cvNews v0.5");
$icon->show_all;
threads->new("retard")->detach();

$programa->signal_autoconnect_from_package();

Gtk2->main;

sub retard {
	my $actualitzar;
	my $delay;
	while (1){
		open (CFG,"$dir/cvnews.conf") or die "No es pot obrir l'arxiu de configuracio!\n";
		while (<CFG>){
			if ($_ =~ /actualitzar=(\d)/){
				$actualitzar=$1;	
			}
			if ($_=~/delay=(\d+)/){	
				$delay=$1;
			}	
		}
		close CFG;
#		print "comprova actualitzar!\n";
		if ($actualitzar eq 1){
			sleep ($delay*60);
			print "Buscant novetats...!\n";
			&update_ico(0);
#			system("perl $dir/cvNews.pl &");
		}
	}
	return 1;
}

sub click {
#	print "Num= ",$_[1]->button,"\n";
	if ($_[1]->button eq 3) {
		&menu($_[1]);	
	}
	return 1;
}

sub update_ico {
#my $thread_act=threads->new("actualitzar")->detach();
#system("perl $dir/cvNews.pl -avisar &");
	my $avisar=shift;
	my $thread_ico = threads->new(sub {
		if ($avisar) {
			open (IN,"perl $dir/cvNews.pl -avisar 2>&1 |");
		}
		else {
			open (IN,"perl $dir/cvNews.pl 2>&1 |");
		}
  		foreach (<IN>){
        	if ($_ =~/Error/){
				1;
           	} 
		}
		close IN;
		0;
		});
	my $thread_idle= threads->new(sub {
		sleep($wait_time_error); # Temps d'espera a que cvNews retorni algo i poder aixi recuperar el thread
		my $err=$thread_ico->join();	# ja que si el recuperava inmediatament després és com si no executes cap thread.
		if ($err){
            $pic->set_from_file($logo_off);
			#	print "Logo off!\n";
		}
		else {
			#	print "Logo on!\n";
            $pic->set_from_file($logo);
		}	
		1;
		});
#	print "Fi update_ico!\n";
	return 1;
}

sub menu {
	my $event=shift;
	my $menu = Gtk2::Menu->new;
	my $item = Gtk2::MenuItem->new ("Actualitzar");
	my $item2 = Gtk2::MenuItem->new ("Opcions");
	my $item4 = Gtk2::MenuItem->new ("Sortir");

 	$menu->append ($item);
	$menu->append(Gtk2::SeparatorMenuItem->new);
   	$menu->append ($item2);
   	$menu->append ($item4);
   	$menu->popup (undef, undef, undef, undef, $event->button, $event->time);
	$menu->show_all;

	# TODO: falta posar que al rebre algun error, el tooltip del trayicon canvi i surti algo rollo error o que no hi ha conexio. Aixi com l'amarok, i que al clicar desaparegui.
	$item->signal_connect('activate' , sub { &update_ico(1); return 1;});
	$item2->signal_connect(activate => sub { 
		my $opcions=$programa->get_widget('opcions');	
		$opcions->show_all;
		&load_op;
   	});
	$item4->signal_connect(activate => sub { 
		Gtk2->main_quit;
		exit();
   	});
}

sub load_op {
	my ($user, $pass,$actualitzar, $delay, $reproduir, $rep_dir);
	my $user_entry=$programa->get_widget('user_entry');
	my $pass_entry=$programa->get_widget('pass_entry');
	my $rep_check=$programa->get_widget('reproduir_check');
	my $rep_filech=$programa->get_widget('rep_filech');
	my $actualitzar_check=$programa->get_widget('actualitzar_check');
	my $delay_spin=$programa->get_widget('delay_spin');
	my $label_actualitzar=$programa->get_widget('label_actualitzar');
	my $label_so=$programa->get_widget('label_so');
		

	open (CFG,"$dir/cvnews.conf");
	foreach (<CFG>){
		if ($_ =~ /reproduir=(\d)/){
       		$reproduir=$1;
    	}
		if ($_ =~ /ubicacio=(\S+)/){
       		$rep_dir=$1;
    	}
		if ($_ =~ /actualitzar=(\d)/){
       		$actualitzar=$1;
    	}
		if ($_ =~ /delay=(\d+)/){
       		$delay=$1;
    	}
		if ($_ =~ /user=(\S+)/){
       		$user=$1;
    	}
   		if ($_ =~ /password=(\S+)/){
        	$pass=$1;
    	}
	}
	close CFG;
	if ($actualitzar eq 0) {
		$actualitzar_check->set_active(0);
		$label_actualitzar->set_sensitive(0);
		$delay_spin->set_sensitive(0);
	}
	else {
		$actualitzar_check->set_active(TRUE);
	}
	if ($reproduir eq 0) {
        $rep_check->set_active(0);
		$label_so->set_sensitive(0);
		$rep_filech->set_sensitive(0);
    }
    else {
        $rep_check->set_active(TRUE);
    }

	$delay_spin->set_value($delay);	
	$rep_filech->set_filename($rep_dir);
	$user_entry->set_text($user);
	my $Rpass= $crypt->decrypt($pass, $seek);
	$pass_entry->set_text($Rpass);
	
	
}
# Signals ##############################################################
#
sub on_reproduir_toggled {
	my $rep_filech=$programa->get_widget('rep_filech');
	my $label_so=$programa->get_widget('label_so');
	my $widget=shift;
	if ($widget->get_active()){
		$label_so->set_sensitive(TRUE);
		$rep_filech->set_sensitive(TRUE);
	}
	else {
		$label_so->set_sensitive(0);
		$rep_filech->set_sensitive(0);
	}
}

sub on_actualitzar_toggled {
    my $delay_spin=$programa->get_widget('delay_spin');
    my $label_actualitzar=$programa->get_widget('label_actualitzar');
	my $widget=shift;
	if ($widget->get_active()){
		$label_actualitzar->set_sensitive(TRUE);
		$delay_spin->set_sensitive(TRUE);
	}
	else {
		$label_actualitzar->set_sensitive(0);
		$delay_spin->set_sensitive(0);
	}
}

sub on_delete_event{
    my $finestra= shift;
    $finestra->hide();
    return 1;
}

sub on_boto_cancelar_clicked {
	my $opcions=$programa->get_widget('opcions');	
	$opcions->hide();
}

sub on_boto_acceptar_clicked {
	my $opcions=$programa->get_widget('opcions');	
	my $user_entry=$programa->get_widget('user_entry');
    my $pass_entry=$programa->get_widget('pass_entry');
    my $rep_check=$programa->get_widget('reproduir_check');
    my $rep_filech=$programa->get_widget('rep_filech');
    my $actualitzar_check=$programa->get_widget('actualitzar_check');
    my $delay_spin=$programa->get_widget('delay_spin');
	my $rep_value;
	my $act_value;
	
	open (CFG,"$dir/cvnews.conf");	
	my @arr=<CFG>;
	my $user=$arr[$#arr-1]; 
	my $pass=$arr[$#arr]; 
	close CFG;

	open (CFG,">$dir/cvnews.conf");	
	
	if ($rep_check->get_active()){
		$rep_value=1
	}
	else {
		$rep_value=0;
	}

	if ($actualitzar_check->get_active()){
		$act_value=1;
	}
	else {
		$act_value=0;
	}		
	chomp($user);
	chomp($pass);
	my $Epass= $crypt->encrypt($pass_entry->get_text(), $seek);

	print CFG "actualitzar=",$act_value,"\n";	
	print CFG "reproduir=",$rep_value,"\n";	
	print CFG "ubicacio=",$rep_filech->get_filename(),"\n";	
	print CFG "delay=",$delay_spin->get_value_as_int(),"\n";	
	print CFG "user=",$user_entry->get_text(),"\n";	
	print CFG "password=",$Epass;	

	$opcions->hide();
	close CFG;
}
