# autodownload flash videos
#
# (c) 2007 by Ralf Ertzinger <ralf@camperquake.de>
# licensed under GNU GPL v2
#
# Based on youtube.pl by Christian Garbs <mitch@cgarbs.de>
# which in turn is
# based on trigger.pl by Wouter Coekaerts <wouter@coekaerts.be>

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

my @grabbers;
my @getters;
my $getter;
my $conf;
my $conffile = File::Spec->catfile(Irssi::get_irssi_dir(), 'videosite.xml');

# activate debug here
my $debug = 0;

# "message public", SERVER_REC, char *msg, char *nick, char *address, char *target
signal_add_last("message public" => sub {check_for_link(\@_,1,4,2,0);});
# "message own_public", SERVER_REC, char *msg, char *target
signal_add_last("message own_public" => sub {check_for_link(\@_,1,2,-1,0);});

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

# "message irc action", SERVER_REC, char *msg, char *nick, char *address, char *target
signal_add_last("message irc action" => sub {check_for_link(\@_,1,4,2,0);});
# "message irc own_action", SERVER_REC, char *msg, char *target
signal_add_last("message irc own_action" => sub {check_for_link(\@_,1,2,-1,0);});

sub write_irssi {
    my $witem = shift;
    my @text = @_;

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

}

sub write_verbose {
    if (Irssi::settings_get_bool('youtube_verbose')) {
        write_irssi(shift, @_);
    }
}

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

sub check_for_link {
    my ($signal,$parammessage,$paramchannel,$paramnick,$paramserver) = @_;
    my $server = $signal->[$paramserver];
    my $target = $signal->[$paramchannel];
    my $message = ($parammessage == -1) ? '' : $signal->[$parammessage];
    my $g;
    my $m;


    my $witem;
    if (defined $server) {
        $witem = $server->window_item_find($target);
    } else {
        $witem = Irssi::window_item_find($target);
    }

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

    # Offer the message to all Grabbers in turn
    foreach $g (@grabbers) {
        if (defined($m = $g->get($message))) {
            write_debug($witem, 'Metadata: %s', Dumper($m));
            write_irssi($witem, '%%R>>> %%NSaving %%Y%s%%N %%G%s', $m->{'SOURCE'}, $m->{'TITLE'});
            unless($getter->get($m)) {
                write_irssi($witem, '%%R>>> FAILED');
            }
        }
    }
}

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(undef, 'videosite: Could not save config: %s', $@);
    } else {
        write_irssi(undef, 'videosite: Saved config');
    }
}

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

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

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

    if (defined($target)) {
        foreach $p (@getters, @grabbers) {
            if ($p->{'NAME'} eq $target) {
                write_irssi(undef, $p->getconfstr());
                return;
            }
        }
        write_irssi(undef, 'No such module');
    } else {
        write_irssi(undef, 'Loaded grabbers:');
        foreach $p (@grabbers) {
            write_irssi(undef, ' ' . $p->{'NAME'});
        };

        write_irssi(undef, 'Loaded getters:');
        foreach $p (@getters) {
            write_irssi(undef, ' ' . $p->{'NAME'});
        };
    }
}

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

    if (defined($target)) {
        foreach $p (@getters, @grabbers) {
            if ($p->{'NAME'} eq $target) {
                write_irssi(undef, $p->gethelpstr());
                return;
            }
        }
        write_irssi(undef, 'No such module');
    } else {
        write_irssi(undef, <<'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
 getter [modulename]: display or set the getter to use
 debug: enable debugging messages
 nodebug: disable debugging messages
EOT
    }
}

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

    if (defined($target)) {
        foreach $p (@getters, @grabbers) {
            if (($p->{'NAME'} eq $target) && ($p->{'TYPE'} eq 'getter')) {
                $getter = $p;
                $conf->{'videosite'}->{'getter'} = $target;
                return;
            }
        }
        write_irssi(undef, 'No such getter');
    } else {
        write_irssi(undef, 'Current getter: %s', $conf->{'videosite'}->{'getter'});
    }
}


# save on unload
sub sig_command_script_unload {
    my $script = shift;
    if ($script =~ /(.*\/)?videosite(\.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(undef, "Trying to load $p:");
        $p =~ s/\.pm$//;
        eval qq{ require $p; };
        if ($@) {
            write_debug(undef, "Failed to load plugin: $@");
            next;
        }

        $g = eval $p.q{->new();};
        if ($@) {
            write_debug(undef, "Failed to instanciate: $@");
            next;
        }

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

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

sub init_videosite {

    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(undef, 'No config found, using defaults');
        $conf = { 'videosite' => { 'getter' => '' }};
    }

    unshift(@INC, File::Spec->catfile(Irssi::get_irssi_dir(), 'scripts', 'videosite'));
    @grabbers = ploader(File::Spec->catfile(Irssi::get_irssi_dir(), 'scripts', 'videosite'), '.*Grabber\.pm$', 'grabber');
    @getters = ploader(File::Spec->catfile(Irssi::get_irssi_dir(), 'scripts', 'videosite'), '.*Getter\.pm$', 'getter');

    unless (defined(@grabbers) && defined(@getters)) {
        write_irssi(undef, 'No grabbers or no getters found, can not proceed.');
        return;
    }

    $getter = $getters[0];
    foreach $p (@getters) {
        if ($conf->{'videosite'}->{'getter'} eq $p->{'NAME'}) {
            $getter = $p;
        }
    }
    write_debug(undef, 'Selected %s as getter', $getter->{'NAME'});
    $conf->{'videosite'}->{'getter'} = $getter->{'NAME'};

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

    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('videosite' => \&cmdhandler);
}

sub cmdhandler {
    my ($data, $server, $item) = @_;
    my @params = split(/\s+/, $data);

    if ($params[0] eq 'save') {
        cmd_save();
    } elsif ($params[0] eq 'set') {
        shift(@params);
        cmd_set(@params);
    } elsif ($params[0] eq 'show') {
        shift(@params);
        cmd_show(@params);
    } elsif ($params[0] eq 'help') {
        shift(@params);
        cmd_help(@params);
    } elsif ($params[0] eq 'getter') {
        shift(@params);
        cmd_getter(@params);
    } elsif ($params[0] eq 'debug') {
        $debug = 1;
        foreach (@grabbers, @getters) {
            $_->setdebug(1);
        }
        write_irssi(undef, 'Enabled debugging');
    } elsif ($params[0] eq 'nodebug') {
        $debug = 0;
        foreach (@grabbers, @getters) {
            $_->setdebug(0);
        }
        write_irssi(undef, 'Disabled debugging');
    }
}

init_videosite();
