#
# This is the 'MainWindow' class of Mchange's glade
#

# babb
# 5/3/2011

package ChoiceBox;
use strict;

use CSL::Gnome2;
use Gnome2;
use Gtk2::GladeXML;

use Mchange;

use Carp;

use Cwd;

### Change this to wherever glade will live.
our $GLADEPATH = '/s/mchange-2.2/lib';

sub new
{
	# Open the glade file to build controls for main window.
	my $this = shift;
	my $class = ref($this) || $this;

	my $self = { };
	bless $self, $class;

	$self->{FORM} = Gtk2::GladeXML->new("$GLADEPATH/mchange-gtk2.glade", 
					"ChoiceBox");

	croak "Error opening Glade file! Check your GLADEPATH." if(!$self->{FORM});

    $self->{FORM}->signal_autoconnect_from_package($self);

    return $self;

}


sub run
{
	my ($class, %params) = @_;

	Gnome2::Program->init("Mchange", "2.2");
	my $form = $class->new;

    # the built-in mchange "menu" thingy is junk and relies on
    # deprecated shit so we will write something new.

    my @lines;

    unless ( $params{strings} ) {
        my $file = $params{file};
        my $dir = getcwd(); # TODO: Change to the actual path later on.
        $file = "$dir/configs/" . $file unless -e $file;


        open (INPUT, "<$file" )
            or die "Couldn't open file $file\n";

        @lines = <INPUT>;
        close INPUT;
    }
    else {
        @lines = @{$params{strings}};
    }

    # Add the lines to the combo box.
    # This should only be used by add/remove hw now, so we don't need special values.
    my @edited_lines;

    foreach my $line ( @lines ) {
        chomp $line;
        next unless $line;
        next if $line =~ /^#/;

        my @toks = split /=/, $line;

        push(@edited_lines, $toks[0]);
    }


    $form->wgt('selection')->set_popdown_strings( @edited_lines );

    $form->wgt('label')->set_text( $params{label} );

    Gtk2->main;

    $form->wgt('ChoiceBox')->hide;

    return $form->{choice};

}

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

    $self->{choice} = "";
    Gtk2->main_quit;
}

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

    $self->{choice} = $self->wgt('seltxt')->get_text();

    Gtk2->main_quit;
}



#
# Helper function to get widget.
#
sub wgt
{
    my ($self, $widget) = @_;
    return $self->{FORM}->get_widget($widget);
}
