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

# babb
# 5/3/2011

package ChangeHW;
use strict;

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

use Mchange;

use GUI::ChoiceBox;

use Carp;

### 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", 
					"ChangeHW");

	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;

    $form->{mach} = $params{machine};
    $form->{curname} = $form->{mach}->cpuname;
    $form->{mc} = $params{mc};

    my $parts = $form->{mach}->get_parts;

    $form->{grey} = Gtk2::Gdk::Color->parse("grey93");
    $form->{white} = Gtk2::Gdk::Color->parse("white");

    # fuck you gtk2 and changing how tree views are done....
    # Columns we need
    my @col_types = ('Glib::String', 'Glib::String', 'Glib::String');
    my @cur_hw_columns = ("Inventory Number", "Description");
    my @new_hw_columns = ("Inventory Number", "Description", "Status");
    $form->{cur_hw_treestore} = Gtk2::TreeStore->new(@col_types);
    $form->wgt('cur_hw')->set_model($form->{cur_hw_treestore});
    $form->{new_hw_treestore} = Gtk2::TreeStore->new(@col_types);
    $form->wgt('changed_hw')->set_model($form->{new_hw_treestore});

    # Add the columns to both treestores.
    for(my $i = 0; $i < @cur_hw_columns; $i++)
    {
        $form->wgt('cur_hw')->insert_column_with_attributes(-1, $cur_hw_columns[$i], 
                Gtk2::CellRendererText->new(), "text", $i);
        $form->wgt('cur_hw')->get_column($i)->set_resizable(1);
    }
        for(my $i = 0; $i < @new_hw_columns; $i++)
    {
        $form->wgt('changed_hw')->insert_column_with_attributes(-1, $new_hw_columns[$i], 
                Gtk2::CellRendererText->new(), "text", $i);
        $form->wgt('changed_hw')->get_column($i)->set_resizable(1);
    }

    # Add the data to the tree view.
    foreach my $invnum (sort keys %$parts) {
        my $part = $parts->{$invnum};
        next if $form->{mc}->transact_query( $invnum);
    
        my $iter = $form->{cur_hw_treestore}->append(undef);
        $form->{cur_hw_treestore}->set(
         $iter,
         0, $invnum,
         1, $part->mdesc );

    }
    


    # Color the rows to make it look prettiful.
    # TODO: Later...maybe...or never.


    $form->wgt('ChangeHW')->set_title( "Hardware update for $form->{curname}" );


    Gtk2->main;

} # End of run

#==============================================================================
# Signal Handlers
#==============================================================================

sub on_ChangeHW_destroy {
  my ($form) = @_;

  exit( 0 ) unless $form->{widget_done};
}

sub on_next_clicked {
  my ($form) = @_;

  $form->{widget_done} = 1; # not sure how this goes into play.
  $form->wgt('ChangeHW')->hide();
  Gtk2->main_quit;
}

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

  $form->wgt('ChangeHW')->hide();
  exit(0); # not sure what this is suppose to do...so I'll just have it exit since that's what mchange currently does
  Gtk2->main_quit;

}

sub on_cur_hw_cursor_changed {
    my ($form) = @_;

    # Get the inventory number and put it in the box.
    # Deselect the other box.
    #$form->wgt('changed_hw')->unselect_all();

    my $selection = $form->wgt('cur_hw')->get_selection();
    my ($model, $iter) = $selection->get_selected();

    if(!$model) { return ; }
    my @values = $model->get($iter);

    # There should only be one value...
    # we care about the first value.
    $form->wgt('invnum')->set_text($values[0]);

}

sub on_changed_hw_cursor_changed {
    my ($form) = @_;

    my $selection = $form->wgt('changed_hw')->get_selection();
    my ($model, $iter) = $selection->get_selected();

    if(!$model) { return ; }
    my @values = $model->get($iter);

    # There should only be one value...
    # we care about the first value.
    $form->wgt('invnum')->set_text($values[0]);
}



sub on_add_clicked {
    my ($form) = @_;

    my $invnum = $form->wgt('invnum')->get_text();
    my $part = $form->{mc}->move_part ( $form->{curname}, $invnum );

    return if $part eq "error";

    # Add it to the what we are doing list:
    # I don't know how to do colors so you'll just have to read what it says.
    my $iter = $form->{new_hw_treestore}->append(undef);
    $form->{new_hw_treestore}->set(
         $iter,
         0, $invnum,
         1, $part->mdesc,
         2, "added");

    # Clear the entry box
    $form->wgt('invnum')->set_text("");


}

sub on_remove_clicked {
    my ($form) = @_;

    my $invnum = $form->wgt('invnum')->get_text();

    return $form->{mc}{eh}->($form->wgt('ChangeHW'), "You need to enter a part number!", 
					'error', 'ok')
        unless $invnum;


    #see if there is a transaction--move_part does this
    #but this is less work for the user ( no SubChoiceBox action )
    if ( my $trans = $form->{mc}->transact_query( $invnum ) ) {
      $form->{mc}{eh}->($form->wgt('ChangeHW'), 
			"Part $invnum scheduled to move to $trans->{machine}--undo transaction first",
			'error', 'ok' );
      $form->{invnum}->delete_text( 0, -1 );
      return;
    }

    #move_part is very general--make sure the part
    #is on the machine the user specified
    my $parts = $form->{mc}->get_machine_parts( $form->{curname} );

    unless ( $parts->{$invnum} ) {
      $form->{mc}{eh}->( $form->wgt('ChangeHW'), "$form->{curname} doesn't have $invnum",
				'error', 'ok' );
      $form->{invnum}->set_text("");
      return;
    }

    my $machine;
    return unless $machine = ChoiceBox->run( file => 'machines',
                                                    label => 'Where is the part going?' );

    # returns "" on cancel.
    return if $machine eq "";

    my $part = $form->{mc}->move_part( $machine, $invnum );

    if ( $part eq "error" ) {
      $form->{invnum}->delete_text( 0, -1 );
      return;
    }

    # Re-create the table of the inventory
    # easiest way I can think of is just to clear the treestore and readd everything
    # since the method will skip over anything we don't need.
    $form->{cur_hw_treestore}->clear();

    # Add the data to the tree view.
    foreach my $invnum (sort keys %$parts) {
        my $part = $parts->{$invnum};
        next if $form->{mc}->transact_query( $invnum);
    
        my $iter = $form->{cur_hw_treestore}->append(undef);
        $form->{cur_hw_treestore}->set(
         $iter,
         0, $invnum,
         1, $part->mdesc );

    }


    # Add the row to our changes list.
    my $iter = $form->{new_hw_treestore}->append(undef);
    $form->{new_hw_treestore}->set(
         $iter,
         0, $invnum,
         1, $part->mdesc,
         2, "removed--$machine");


    $form->wgt('invnum')->set_text("");

}

sub on_undo_clicked {
    # For now, just record that we undid that action.
    # since treestores are annoying to delete shit from.

    my ($form) = @_;

    my $invnum = $form->wgt('invnum')->get_text;

    my $part = $form->{mc}->undo_move_part ( $invnum );

    return if $part eq "error";

    my $iter = $form->{new_hw_treestore}->append(undef);
    $form->{new_hw_treestore}->set(
         $iter,
         0, $invnum,
         1, $part->mdesc,
         2, "undid previous move");

   # Recreating the cur_hw one *should* readd things we removed.
   $form->{cur_hw_treestore}->clear();

    # Add the data to the tree view.
    my $parts = $form->{mc}->get_machine_parts( $form->{curname} );
    foreach my $invnum (sort keys %$parts) {
        my $part = $parts->{$invnum};
        next if $form->{mc}->transact_query( $invnum);
    
        my $iter = $form->{cur_hw_treestore}->append(undef);
        $form->{cur_hw_treestore}->set(
         $iter,
         0, $invnum,
         1, $part->mdesc );

    }

    $form->wgt('invnum')->set_text("");



}

sub on_import_file_clicked
{
    my ($form) = @_;

}

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

