#!/usr/bin/perl -w

#   Decide
#   Copyright (C) 2009  Jernej Simoncic
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
#
#Changelog:
#
#2009-08-26: 0.1
# - initial release

use strict;
use warnings;

my $chanmatch = qr=
					\#(?:channel|list|here)
                  =ix;

my %oldstuff;

##
# server_hook: Handle messages from server
#
sub server_hook
{
	unless ($_[1][0] =~ /^:(([^!]+)!([^@]+)@(\S+)) PRIVMSG (\S+) :(.*)$/) {
		return Xchat::EAT_NONE;
	}

	my $mask = $1;
	my $nick = lc($2);
	my $ident = $3;
	my $host = $4;
	my $dest = lc($5);
	my $msg = Xchat::strip_code(lc($6));

	return Xchat::EAT_NONE unless $dest =~ $chanmatch;
	return Xchat::EAT_NONE unless $msg =~ /^([!\.]decide) (.*)$/;

	decide($dest,$2,$nick);

	return Xchat::EAT_NONE;
}

sub decide($$)
{
	my ($where,$what,$who) = @_;

	my @stuff = sort(split(m,/,,$what));
	s:^\s+|\s+$::g foreach @stuff;

	my %uniquestuff;
	$uniquestuff{lc($_)} = $_ foreach @stuff;
	@stuff = ();
	push @stuff,$uniquestuff{$_} foreach keys %uniquestuff;

	my $current = lc(join('/',sort(@stuff)));

	my $decision;

	if (@stuff == 1) {
		Xchat::command 'say What would you like me to decide on?!';
		return;
	}

	if (exists($oldstuff{$who})) {
		foreach my $old (@{$oldstuff{$who}}) {
			if ($old->{what} eq $current) {
				$decision = $old->{decision};
				$old->{when} = time();
				if ($decision eq '/') {
					Xchat::command 'say Decide for yourself!';
				} else {
					Xchat::command 'say The decision has been made before: ' . $decision;
				}
				return;
			}
		}
	}

	if (!defined($decision)) {
		$decision = $stuff[int(rand(@stuff))];
		$decision = '/' if (int(rand(30)) == 1);
		push @{$oldstuff{$who}},{what => $current,decision => $decision, when => time()};
		if ($decision eq '/') {
			Xchat::command 'say Decide for yourself!';
		} else {
			Xchat::command 'say The decision has been made: ' . $decision;
		}
	}

}

sub tmr_expire_old_decisions
{
	my $now = time;
	foreach my $who (keys %oldstuff) {
		for (my $i = $#{$oldstuff{$who}}; $i >= 0; $i--) {
			if ($now - $oldstuff{$who}->[$i]->{when} > 1200) {
				splice @{$oldstuff{$who}},$i,1;
			}
		}
	}

	return Xchat::KEEP;
}

Xchat::register("Decide", "0.1", "Decider");
Xchat::hook_server("PRIVMSG", \&server_hook);
Xchat::hook_timer(10000, \&tmr_expire_old_decisions);
