# -*- mode: perl; coding: utf-8 -*-
# Keitairc::Plugins
#
# Copyright (c) 2008 Jun Morimoto <morimoto@mrmt.net>
# This program is covered by the GNU General Public License 2

package Keitairc::Plugins;
use Encode;
use strict;
use warnings;

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

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

################################################################
sub list_plugins{
	my $me = shift;
	sort { $me->{plugins}->{$a}->{order} - $me->{plugins}->{$b}->{order} } 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}->{order} - $me->{plugins}->{$b}->{order} } keys %{$me->{plugins}}
		);
}

################################################################
sub list_action_plugins{
	my $me = shift;
	grep(
		defined($me->{plugins}->{$_}->{action_imprementation}),
		sort { $me->{plugins}->{$a}->{order} - $me->{plugins}->{$b}->{order} } 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->log_die("Error in plugin $dir/$file\n" . $@);
						next;
					}

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

					if(defined $plugins->{$plugin->{name}}){
						$::log->log_die("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++;

					unless($me->{silent}){
						$::log->log("Loaded plugin $plugin->{name} from $dir/$file");
					}
				}
			}
			closedir(F);
		}
	}
	$me->{plugins} = $plugins;
}

1;
