# -*-perl-*-
# Keitairc::Plugins
# $Id: Plugins.pm,v 1.1 2008/01/09 18:48:04 morimoto Exp $
# $Source: /cvsroot/keitairc/lib/Keitairc/Plugins.pm,v $
#
# Copyright (c) 2008 Jun Morimoto <morimoto@mrmt.net>
# This program is covered by the GNU General Public License 2

package Keitairc::Plugins;
use strict;

################################################################
sub new{
	my $proto = shift;
	my $arg = shift;
	my $me = {};
        bless $me;

	$me->{Config} = $arg->{config};
	$me->{plugins} = {};
	$me->load_plugins();
	$me;
}

################################################################
sub list_plugins{
	my $me = shift;
	sort { $me->{plugins}->{$a} - $me->{plugins}->{$b} } keys %{$me->{plugins}};
}

################################################################
sub list_replace_plugins{
	my $me = shift;
	grep(
		defined($me->{plugins}->{$_}->{message_replace_regexp}) &&
		defined($me->{plugins}->{$_}->{message_replace_imprementation}),
		sort { $me->{plugins}->{$a} - $me->{plugins}->{$b} } keys %{$me->{plugins}}
		);
}

################################################################
sub list_action_plugins{
	my $me = shift;
	grep(
		defined($me->{plugins}->{$_}->{action_imprementation}),
		sort { $me->{plugins}->{$a} - $me->{plugins}->{$b} } keys %{$me->{plugins}}
		);
}

################################################################
sub load_plugins{
	my $me = shift;
	my $plugins = {};
	my $order = 0;
	for my $dir (split(':', $me->{Config}->plugin_dir())){
		if(opendir(F, $dir)){
			for my $file (sort(grep(/^\d\d/, readdir(F)))){
				if(open(P, "$dir/$file")){
					my $plugin = {};
					my $e = eval join('', <P>);
					close(P);
					if($@ || !defined($e)){
						::log("Error in plugin $dir/$file");
						::log($@);
						next;
					}

					unless($plugin->{name} =~ /^[a-z][a-z0-9_]+/){
						::log("Illegal plugin name $plugin->{name}");
						next;
					}

					if(defined $plugins->{$plugin->{name}}){
						::log("Plugin $plugin->{name} has already loaded");
						next;
					}

					$plugins->{$plugin->{name}}->{message_replace_regexp} =
						$plugin->{message_replace_regexp};
					$plugins->{$plugin->{name}}->{message_replace_imprementation} =
						$plugin->{message_replace_imprementation};
					$plugins->{$plugin->{name}}->{action_imprementation} =
						$plugin->{action_imprementation};
					$plugins->{$plugin->{name}}->{order} = $order++;
					::log("Loaded plugin $plugin->{name} from $dir/$file");
				}
			}
			closedir(F);
		}
	}
	$me->{plugins} = $plugins;
}

1;
