package Milkbone::AddBuddy;

use Milkbone;

our $VERSION = '1.0';

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

Construct Tk::Widget 'MBAddBuddy';

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

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

sub on_add {
    my ($self) = @_;

    my $name = $self->{entry}->get();
    my $group = $self->{group};
    hook("protocol_add_buddy", -group => $group, -buddy => $name);    
    hook("protocol_commit_blist");
	$self->destroy;
}

sub init
{
	my ($self) = @_;

	$self->withdraw;

	my $groups = hook("protocol_get_groups");
	$self->configure(-title => "Add Buddy");
	$self->{group} = "";
	$self->focus();
	$self->Frame->pack(-expand => 1, -fill => 'both');
	$self->Frame->pack(-expand => 1, -fill => 'both');
	$self->{buttons} = $self->Frame;

	$self->Label(-text => 'Screen name:', -anchor=>'w')->pack();
	$self->{entry} = $self->Entry( 
		-background => 'white', -width => 16, -takefocus => 1)->pack(-expand => 1, -fill => 'both', -padx => 4);

	$self->Label(-text => 'Group:', -anchor=>'w')->pack();
	$self->{list} = $self->JBrowseEntry(-width => 16, -takefocus => 1, -variable => \$self->{group},
		-choices => [sort @$groups])->pack(-expand => 1, -fill => 'both');
	
	$self->{buttons}->Button(-text => "Cancel", -command => [ $self, "destroy"])->pack(-pady => 6,  -padx=>6, -side=>'right');
	$self->{buttons}->Button(-text => "Add", -command => [ $self, "on_add"])->pack(-pady => 6,  -padx=>6, -side=>'right');
	$self->{buttons}->pack;
	
	$self->bind('<Return>' => [$self, 'on_add']);
	$self->bind("<Escape>" => [$self, "destroy"]);
	hook("tk_seticon", -wnd => $self);

	$self->{group} = $groups->[0];

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

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

1;