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

$VERSION = "0.0.3";

%IRSSI = (
    authors     =>  "Sebastian Groeneveld",
    contact     =>  "dracuul78\@hotmail.com",
    name        =>  "search",
    description =>  "Searches the logs for regexp and shows the most recent result",
    license     =>  "GPL v2 and any later",
);

my %querytime;

sub do_searchnow {
    my ($server, $channel, $nick, $cmd, $query, $num, $tail) = @_;

    my $response = call_query_service($channel, $query, $num, $tail);
    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, "No match found for '". $query ."' in ". $channel );
    }
}

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

    my $queryUrl = sprintf("http://venstraat.hopto.org/irclog/webapi.php?c=%s&r=%d&x=%d&n=%s&f=1&q=^[^%20]*.*%s.*", uri_escape($channel), ($tail ? 1 : 0), ($tail ? 1 : 0), 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_searchnow($server, $target, $server->{nick}, $msg);
}

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

sub check_searchnow {
    my ($server, $target, $nick, $msg) = @_;

    my $tail;

    if ($msg =~ /^!searchlast\s+.*/ ) {
        $tail = 1;
    } elsif ($msg =~ /^!searchfirst\s+.*/) {
        $tail = 0;
    } else {
        return;
    }
    #return unless $msg =~ '^!searchlast\s+.*';
    return unless $target =~ '#dingetje' or $target =~ '#bwrrp';

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

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

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

    threads->new(\&do_searchnow, $server, $target, $nick, $cmd, $query, $num, $tail);
    #do_searchnow($server, $target, $query, $num, $tail);
}

#
# send message to specified nick
#
sub outmsg {
    my ($server, $target, $msg) = @_;
    
    #print( CRAP "Sending raw PRIVMSG" );
    $server->send_raw("PRIVMSG $target :$msg");
}

sub outpubmsg {
    my ($server, $target, $msg) = @_;
    
    #print( CRAP "Sending command 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 "Search loaded." );