use Irssi;
use Time::HiRes qw(time);
use URI::Escape;
use LWP::UserAgent;
use threads;
use strict;
use vars qw($VERSION %IRSSI);

$VERSION = "0.0.4";

%IRSSI = (
    authors     =>  "Sebastian Groeneveld",
    contact     =>  "dracuul78\@hotmail.com",
    name        =>  "seen",
    description =>  "Triggers on !seen and displays the last line said by the specified nickname",
    license     =>  "GPL v2 and any later",
);

my $_globalthrottle;

#-----------------------------------------------------
sub do_seen {
#-----------------------------------------------------
    my ($server, $channel, $query, $num) = @_;
 
    my $response = call_query_service($channel, $query, $num);

    if (!$response->is_success)
    {
        outpubmsg($server, $channel,  "Unable to execute query (" . $response->status_line . ")");
        return;
    }

    # utf-8 compatible
    my $content = $response->decoded_content;

    my $found = 0;
    foreach (split /^/, $content) {
        chomp;
        next unless (/[^ ]/);
        outpubmsg($server, $channel, $_);
        $found = 1;
    }

    if (!$found)
    {
        outpubmsg( $server, $channel, "Nobody with nick '". $query ."' has ever said anything in ". $channel );
    }
}

#-----------------------------------------------------
sub call_query_service {
#-----------------------------------------------------
    my ($channel, $query, $num) = @_;

    my $queryUrl = sprintf("http://venstraat.hopto.org/irclog/webapi.php?c=%s&r=1&n=%s&f=1&q=^[^%20]*%20%3C[@%2B*]?%s%3E.*", uri_escape($channel), uri_escape($num), uri_escape($query));

    my $ua = new LWP::UserAgent;
    my $response = $ua->get($queryUrl);

    return $response;
}

#-----------------------------------------------------
sub sig_message_ownpublic {
#-----------------------------------------------------
    my ($server, $msg, $target) = @_;
    check_seen($server, $target, $server->{nick}, $msg);
}


#-----------------------------------------------------
sub sig_message_public {
#-----------------------------------------------------
    my ($server, $msg, $nick, $address, $target) = @_;
    check_seen($server, $target, $nick, $msg);
}


#-----------------------------------------------------
sub check_seen {
#-----------------------------------------------------
    my ($server, $target, $sender, $msg) = @_;

    return unless $msg =~ '^!seen *';
    return unless $target =~ '#dingetje' or $target =~ '#bwrrp';

    my ($cmd, $query, $num) = split(/ /, $msg, 3);

    # replace whitespace with + symbols
    $query =~ s/'//g;
    $query =~ s/\|/\\|/g;

    if ($num < 1) {
        $num = 1;
    } elsif ($num > 6) {
        $num = 6;
    }

    if (length $query < 3) {
        outprivmsg( $server, $sender, "Command ignored, search string too short..." );
    } elsif (time - $_globalthrottle < 5) {
        outprivmsg( $server, $sender, "Command ignored, must wait longer between queries..." );
    } else {
        $_globalthrottle = time;
        #outpubmsg( $server, $target, "Searching...");
        threads->new(\&do_seen, $server, $target, $query, $num);
    }
}
#
# send message to specified nick
#
#-----------------------------------------------------
sub outprivmsg {
#-----------------------------------------------------
    my ($server, $target, $msg) = @_;
    
    $server->send_raw("PRIVMSG $target :$msg");
}

#-----------------------------------------------------
sub outpubmsg {
#-----------------------------------------------------
    my ($server, $target, $msg) = @_;
    
    $server->command("MSG $target $msg");
}

#
# Install signal handlers
# 
Irssi::signal_add_first( 'message public',     \&sig_message_public );
Irssi::signal_add_first( 'message own_public', \&sig_message_ownpublic );
print( CRAP "Seen loaded." );