#
# This class is a application-interface-class,
# that handles theme-plugins
# 		written by ...: geronimo at vdrportal dot de
# 
# COPYRIGHT:	(c) 2006 Creative Commons by-nc-sa
#					some rights reserved. For details on copyright see:
#					http://creativecommons.org/licenses/by-nc-sa
#
# DISCLAIMER:	NO WARANTY AT ALL. Use at your own risk.
# 
# vi: ts=3
#
package V2I::PluginManager;

use Data::Dumper;
use Carp qw(carp croak);

use strict;

our $debug;

sub new {
	my $class = shift;
	my $self = {
		  -plugindir => '/usr/share/jobedit/plugins'	  
		, -appconfig => {}		 
		};
	bless($self, $class);
	$self->populate(@_);
	$self->initialize();

	return $self;
}

sub populate {
	my $self = shift;

	print('PluginManager::populate() ... Args:'."\n".Dumper(\@_)."\n") if $debug;
	while(my $vn = shift){
		if($vn eq '-plugindir') {	$self->{$vn} = shift; } 
		elsif($vn eq '-appconfig') { $self->{$vn} = shift; }
		else { croak('unknown parameter: '.$vn); }
		}
}

sub initialize {
	my $self = shift;
	my $dp;

	if(opendir($dp, $self->{'-plugindir'})){
		my $base = $self->{'-plugindir'};

		$base .= '/' if not $base =~ /\/$/;
		$self->{'activeplugins'} = ();	  
		while(my $de = readdir($dp)){
			if($de =~ /^(.+?)\.pm$/ and -s $base.$de){
				next if $de =~ /^Theme(?:.+?)$/;	 # themes have their own manager, so skip em 
				my $pluginClass = $1;
				my $moduleName = 'V2I::plugins::'.$pluginClass;

				print('check for plugin <'.$pluginClass.'>, ['.$moduleName."]\n") if $debug;
				
				eval "require $moduleName";
				if($moduleName->isa('V2I::Plugin')){
					if($self->{'-appconfig'}){
						$self->{'activeplugins'}{$pluginClass} = $moduleName->new($self->{'-appconfig'}{$pluginClass});	  
						}
					else{
						$self->{'activeplugins'}{$pluginClass} = $moduleName->new;	  
						}
					}
				else{ print("\t".'class <'.$moduleName.'> seems to be no Plugin!?!'."\n") if $debug; }	
				}
			}
		closedir($dp);
		}
}

sub getPlugin {
	my $self = shift;
	my $plugin = shift;

	croax($plugin.' is not an active plugin!') if not defined($self->{'activeplugins'}{$plugin});
	
	return $self->{'activeplugins'}{$plugin};
}

sub dump {
	my $self = shift;	  

	print(__PACKAGE__.' looks like this: ...'."\n".Dumper($self)."\n");	  
}

1;
__END__
