package Milkbone::PluginsConf;

use Milkbone;
use Milkbone::PluginLoad;

our $VERSION = '1.0';

use Tk::widgets qw(Frame);
use base qw(Tk::Toplevel);
use strict;
use warnings;

Construct Tk::Widget 'MBPluginsConf';

sub ClassInit
{
	my ($class, $mw) = @_;
	$class->SUPER::ClassInit($mw);
}

sub Populate
{
	my ($self, $args) = @_;
	$self->SUPER::Populate($args);
}

sub on_add
{
	my ($self) = @_;
	my $load_dlg = $self->MBPluginLoad;
	$load_dlg->init($self);
}

sub on_delete
{
	my ($self) = @_;
	my $sel = $self->{list}->curselection;

	return unless $sel;

	my $plugin = $self->{list}->get($sel);

	unload_plugin($plugin);
	$self->{list}->delete($sel);
}

sub on_reload
{
	my ($self) = @_;
	my $sel = $self->{list}->curselection;

	unless($sel)
        {
            warn "Choose an item from the list.";
            return;
        }

	my $plugin = $self->{list}->get($sel);

	unload_plugin($plugin);	
        load_plugin($plugin);
	init_plugin($plugin);
}


sub init
{
	my ($self) = @_;
	$self->withdraw;
	$self->configure(-title => "Configure Plugins");
	$self->focus();

	$self->Label(-text => 'Plugins:')->pack(-fill => 'both', -expand => 1);

	$self->{left} = $self->Frame->pack(-side => 'left', -padx => 2, -pady => 2);
	$self->{right} = $self->Frame->pack(-side => 'right');

	$self->{list} = $self->{left}->Scrolled("Listbox", -scrollbars => 'oe', -background => 'white')->pack(-expand => 1, -fill => 'y');

	$self->{list}->insert('end', sort(@{hook("loaded_plugins")}));

	$self->Button(-text => "Load...", -command => [ $self, "on_add"])->pack(-pady => 6,  -padx => 6);
	$self->Button(-text => "Unload", -command => [ $self, "on_delete"])->pack(-pady => 6,  -padx => 6);
	$self->Button(-text => "Reload", -command => [ $self, "on_reload"])->pack(-pady => 6,  -padx => 6);
	
	$self->bind('<Return>' => [$self, 'on_apply']);
	$self->bind("<Escape>" => [$self, "destroy"]);
	hook("tk_seticon", -wnd => $self);

	$self->update;
	$self->geometry("+" . int(($self->screenwidth() / 2) - int($self->width() / 2)) . "+" . int(($self->screenheight() / 2) - int($self->height() / 2)) );
	$self->deiconify;

	hook("tk_bindwheel", -window => $self->{list});

	$self->update();
	$self->focus;
}

1;