# autodisplay quotes from quotesites
#
# (c) 2007-2008 by Ralf Ertzinger <ralf@camperquake.de>
# licensed under GNU GPL v2


BEGIN {
    # Get rid of a (possibly old) version of BettIrssi
    # This is a hack to prevent having to reload irssi just
    # because BettIrssi.pm changed

    delete($INC{'BettIrssi.pm'});
}

use strict;
use Irssi 20020324 qw (command_bind command_runsub signal_add_first signal_add_last window_find_refnum);
use vars qw($VERSION %IRSSI);
use XML::Simple;
use Data::Dumper;
use File::Spec;
use BettIrssi 101 qw(_bcb _bcs);

my @grabbers;
my $conf;
my $conffile = File::Spec->catfile(Irssi::get_irssi_dir(), 'quotesite.xml');
my $plugindir = File::Spec->catfile(Irssi::get_irssi_dir(), 'scripts', 'quotesite');
my @outputstack = (undef);

my $PARAMS = {
};


# activate debug here
my $debug = 0;

# "message public", SERVER_REC, char *msg, char *nick, char *address, char *target
signal_add_last(_bcs("message public" => sub {check_for_link(@_)}));
# "message own_public", SERVER_REC, char *msg, char *target
signal_add_last(_bcs("message own_public" => sub {check_for_link(@_)}));

# "message private", SERVER_REC, char *msg, char *nick, char *address
signal_add_last(_bcs("message private" => sub {check_for_link(@_)}));
# "message own_private", SERVER_REC, char *msg, char *target, char *orig_target
signal_add_last(_bcs("message own_private" => sub {check_for_link(@_)}));

# "message irc action", SERVER_REC, char *msg, char *nick, char *address, char *target
signal_add_last(_bcs("message irc action" => sub {check_for_link(@_)}));
# "message irc own_action", SERVER_REC, char *msg, char *target
signal_add_last(_bcs("message irc own_action" => sub {check_for_link(@_)}));

sub push_output {
    unshift(@outputstack, shift);
}

sub pop_output {
    shift(@outputstack);

    @outputstack = (undef) unless (@outputstack);
}

my $quotesite_commands = {
    'save' => sub {
        cmd_save();
    },


    'set' => sub {
        cmd_set(@_);
    },

    'show' => sub {
        cmd_show(@_);
    },

    'help' => sub {
        cmd_help(@_);
    },

    'enable' => sub {
        cmd_enable(@_);
    },

    'disable' => sub {
        cmd_disable(@_);
    },

    'reload' => sub {
        init_quotesite(0);
    },

    'debug' => sub {
        $debug = 1;
        foreach (@grabbers) {
            $_->setdebug(1);
        }
        write_irssi('Enabled debugging');
    },

    'nodebug' => sub {
        $debug = 0;
        foreach (@grabbers) {
            $_->setdebug(0);
        }
        write_irssi('Disabled debugging');
    },
};


sub write_irssi {
    my @text = @_;
    my $output = $outputstack[0];

    my $format = "%%mquotesite: %%n" . shift(@text);

    # escape % in parameters for irssi
    s/%/%%/g foreach @text;

    if (defined($output)) {
        $output->(sprintf($format, @text), MSGLEVEL_CLIENTCRAP);
    } else {
        Irssi::print(sprintf($format, @text));
    }

}

sub write_debug {
    if ($debug) {
        write_irssi(@_);
    }
}

sub check_for_link {
    my $event = shift;
    my $message = $event->message();
    my $channel = $event->channel();
    my $g;
    my $m;
    my $p;


    # Look if we should ignore this line
    if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
        return;
    }

    push_output($event->ewpf);

    study($message);

    # Offer the message to all Grabbers in turn
    foreach $g (@grabbers) {
        ($m, $p) = $g->get($message);
        while (defined($m)) {
            write_irssi('%%R>>> %%Y%s%%N %%G%s', $m->{'SOURCE'}, $m->{'ID'});

            foreach (split(/[\n\r]+/, $m->{'CONTENT'})) {
                write_irssi('    %%g%s', $_);
            }

            # Remove the matched part from the message and try again (there may be
            # more!)
            $message =~ s/$p//;
            study($message);

            ($m, $p) = $g->get($message);
        }
    }

    pop_output();
}

sub cmd_save {

    eval {
        open(CONF, '>'.$conffile) or die 'Could not open config file';
        print CONF XML::Simple::XMLout($conf, KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'});
        close(CONF);
    };
    if ($@) {
        write_irssi('Could not save config to %s: %s', ($conffile, $@));
    } else {
        write_irssi('configuration saved to %s', $conffile);
    }
}

sub cmd_set {
    my $target = shift;
    my $key = shift;
    my $val = shift;
    my $p;

    foreach $p (@grabbers) {
        if ($p->{'NAME'} eq $target) {
            $p->setval($key, $val);
            return;
        }
    }
    write_irssi('No such module');
}


sub cmd_enable {
    my $target = shift;
    my $p;

    foreach $p (@grabbers) {
        if ($p->{'NAME'} eq $target) {
            $p->enable();
            return;
        }
    }
    write_irssi('No such module');
}


sub cmd_disable {
    my $target = shift;
    my $p;

    foreach $p (@grabbers) {
        if ($p->{'NAME'} eq $target) {
            $p->disable();
            return;
        }
    }
    write_irssi('No such module');
}


sub cmd_show {
    my $target = shift;
    my $p;
    my $e;

    if (defined($target)) {
        foreach $p (@grabbers) {
            if ($p->{'NAME'} eq $target) {
                write_irssi($p->getconfstr());
                return;
            }
        }
        write_irssi('No such module');
    } else {
        write_irssi('Loaded grabbers (* denotes enabled modules):');
        foreach $p (@grabbers) {
            $e = $p->_getval('enabled');
            write_irssi(' %s%s', $p->{'NAME'}, $e?'*':'');
        };
    }
}

sub cmd_help {
    my $target = shift;
    my $p;

    if (defined($target)) {
        foreach $p (@grabbers) {
            if ($p->{'NAME'} eq $target) {
                write_irssi($p->gethelpstr());
                return;
            }
        }
        write_irssi('No such module');
    } else {
        write_irssi(<<'EOT');
Supported commands:
 save: Save the current configuration
 help [modulename]: Display this help, or module specific help
 show [modulename]: Show loaded modules, or the current parameters of a module
 set modulename parameter value: set a module parameter to a new value
 enable [modulename]: enable the usage of this module (grabbers only)
 disable [modulename]: disable the usage of this module (grabbers only)
 reload: reload all modules (this is somewhat experimental)
 debug: enable debugging messages
 nodebug: disable debugging messages
EOT
    }
}

# save on unload
sub sig_command_script_unload {
    my $script = shift;
    if ($script =~ /(.*\/)?quotesite(\.pl)?$/) {
        cmd_save();
    }
}

sub ploader {

    my $dir = shift;
    my $pattern = shift;
    my $type = shift;
    my @list;
    my $p;
    my $g;
    my @g = ();

    opendir(D, $dir) || return ();
    @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
    closedir(D);

    foreach $p (@list) {
        write_debug("Trying to load $p:");
        $p =~ s/\.pm$//;
        eval qq{ require quotesite::$p; };
        if ($@) {
            write_debug("Failed to load plugin: $@");
            next;
        }

        $g = eval qq{ quotesite::$p->new(); };
        if ($@) {
            write_debug("Failed to instanciate: $@");
            delete($INC{$p});
            next;
        }

        write_debug("found $g->{'TYPE'} $g->{'NAME'}");
        if ($type eq $g->{'TYPE'}) {
            push(@g, $g);
            $g->setio(\&write_irssi);
        } else {
            write_irssi('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
            delete($INC{$p});
        }
    }

    write_debug("Loaded %d plugins", $#g+1);
    
    return @g;
}

sub _load_modules($) {

    my $path = shift;

    foreach (keys(%INC)) {
        if ($INC{$_} =~ m|^$path|) {
            write_debug("Removing %s from \$INC", $_);
            delete($INC{$_});
        }
    }
    @grabbers = ploader($path, '.*Grabber\.pm$', 'grabber');
}


sub init_quotesite {

    my $bindings = shift;
    my $p;

    unless(-r $conffile && defined($conf = XML::Simple::XMLin($conffile, ForceArray => ['config', 'option'], KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'}))) {
        # No config, start with an empty one
        write_debug('No config found, using defaults');
        $conf = { 'quotesite' => { }};
    }
    foreach (keys(%{$PARAMS})) {
        unless (exists($conf->{'quotesite'}->{$_})) {
            $conf->{'quotesite'}->{$_} = $PARAMS->{$_};
        }
    }

    _load_modules($plugindir);

    unless (@grabbers) {
        write_irssi('No grabbers found, can not proceed.');
        return;
    }


    # Loop through all plugins and load the config
    foreach $p (@grabbers) {
        $conf->{'quotesite'}->{'config'}->{$p->{'NAME'}} = $p->mergeconfig($conf->{'quotesite'}->{'config'}->{$p->{'NAME'}});
    }

    if ($bindings) {

        Irssi::signal_add_first('command script load', 'sig_command_script_unload');
        Irssi::signal_add_first('command script unload', 'sig_command_script_unload');
        Irssi::signal_add('setup saved', 'cmd_save');


        Irssi::command_bind(_bcb('quotesite' => \&cmdhandler));
    }

    write_irssi('quotesite initialized');
}

sub cmdhandler {
    my $event = shift;
    my ($cmd, @params) = split(/\s+/, $event->message());

    push_output($event->ewpf);

    if (exists($quotesite_commands->{$cmd})) {
        $quotesite_commands->{$cmd}->(@params);
    }

    pop_output();
}

unshift(@INC, $plugindir);
init_quotesite(1);
