##
## Put me in ~/.irssi/scripts, and then execute the following in irssi:
##
##       /load perl
##       /script load espeak
##

# Nearly everything comes from the script notify
# Use this only if you are really crazy and don't tell your friends you
# have such a stupid thing !

use strict;
use Irssi;
use vars qw($VERSION %IRSSI);
use String::Escape qw/quote/;

$VERSION = "0.01";
%IRSSI = (
    authors     => 'Olivier Schwander',
    contact     => 'olivier.schwander@ens-lyon.org',
    name        => 'espeak.pl',
    description => 'Use espeak to alert user to hilighted messages',
    license     => 'GNU General Public License',
    url         => 'http://chadok.info/irssi/',
);

Irssi::settings_add_str('espeak', 'espeak_voice', 'fr');

sub espeak {
    my ($server, $summary, $message) = @_;

    # Make the message entity-safe
    $message =~ s/&/&amp;/g; # That could have been done better.
    $message =~ s/</&lt;/g;
    $message =~ s/>/&gt;/g;
    $message =~ s/\'/&apos;/g;

    my $cmd = "EXEC - espeak -m" .
    " -v " . Irssi::settings_get_str('espeak_voice') .
    " '" . quote($message) . "' 1>/dev/null 2>&1";

    $server->command($cmd);
}

sub print_text_espeak {
    my ($dest, $text, $stripped) = @_;
    my $server = $dest->{server};

#    return if (!$server);
    return if (!$server || !($dest->{level} & MSGLEVEL_HILIGHT));
    my $sender = $stripped;
    $sender =~ s/^\<.([^\>]+)\>.+/\1/ ;
    $stripped =~ s/^\<.[^\>]+\>.// ;
    my $summary = $dest->{target} . ": " . $sender;
    espeak($server, $summary . $dest->{level},  $stripped);
}

sub message_private_espeak {
    my ($server, $msg, $nick, $address) = @_;

    return if (!$server);
    espeak($server, "Private message from ".$nick, $msg);
}

sub beep_espeak {
    my ($server, $msg, $nick, $address) = @_;

    return if (!$server);
    espeak($server, "Beep".$nick, $msg);
}

sub dcc_request_espeak {
    my ($dcc, $sendaddr) = @_;
    my $server = $dcc->{server};

    return if (!$dcc);
    espeak($server, "DCC ".$dcc->{type}." request", $dcc->{nick});
}

Irssi::signal_add('print text', 'print_text_espeak');
Irssi::signal_add('message private', 'message_private_espeak');
Irssi::signal_add('dcc request', 'dcc_request_espeak');
Irssi::signal_add('beep', 'beep_espeak');
