use strict;
use Win32::GUI;
use Win32::GUI::EZ::ListView;

my $test_data = {
 1 => {
  fname => 'john',
  lname => 'smith',
  bday => '8/1/2002',
  money => '500.82'
      },
 2 => {
  fname => 'john',
  lname => 'doe',
  bday => '8/01/1402',
  money => '1.04'
      },
 3 => {
  fname => 'jane',
  lname => 'smith',
  bday => '1/1/1999',
  money => '1,928,347'
      },
 4 => {
  fname => 'icabod',
  lname => 'crane',
  bday => '8/31/2002',
  money => '$3,500'
      },
 5 => {
  fname => 'john',
  lname => 'smith',
  bday => '06/02/1950',
  money => '0.25'
      },
};

my $win = new Win32::GUI::Window(
  -name => 'win',
  -left => 100,
  -top => 100,
  -width => 450,
  -height => 350,
  -text => 'EZ Listview Test'
);

my $lv = Win32::GUI::EZ::ListView->new(
  -name => 'lv',
  -left => 10,
  -top => 10,
  -width => 430,
  -height => 250,
  -parent => $win,
  -singlesel => 1,
  -fullrowselect => 1,
);

my $button = $win->AddButton (
  -name => 'btn',
  -top => 270,
  -left => 20,
  -text => 'test',
  -onClick => \&clicker,
);

# you can populate from a database:
# my $sql = 'select * from people';
# $lv->sql_populate($dbh, $sql, 'person_id');
#
# or populate using a hashref of hashrefs (see the above definition of $test_data)
$lv->import_hashref($test_data);

# refer to columns by the underlying column name
$lv->fname->width(100);

# give the column a nicer name
$lv->lname->text("Last Name");

# don't let users sort by last name
# all sorting can be disabled with $lv->{-can_sort} = 0
$lv->lname->{-can_sort} = 0;

$lv->add(12, { fname => 'bob', lname=>'smith', bday => '6/7/1974'});

# define custom sorting subrefs
my $datesort = sub {
  my ($arg, $arg2) = @_;
  $arg =~ m|^(\d+)/(\d+)/(\d+)|;
  $arg = sprintf('%02d%02d%02d', $3, $1, $2);
  $arg2 =~ m|^(\d+)/(\d+)/(\d+)|;
  $arg2 = sprintf('%02d%02d%02d', $3, $1, $2);
  return $arg <=> $arg2;
};

my $moneysort = sub {
  my ($arg, $arg2) = @_;
  $arg =~ s/[\$\,]//g;
  $arg2 =~ s/[\$\,]//g;
  return $arg <=> $arg2;
};

# assign the subrefs to the listview
$lv->money->sorter($moneysort);
$lv->bday->sorter($datesort);

# tell the listview which columns to show in which order
$lv->display_columns(qw/fname lname bday money/);

$win->Center;
$win->Show;

#Win32::GUI::DoEvents();
#sleep(2);
#
# # remove a row
#$lv->remove(4);
#$lv->redraw;

Win32::GUI::Dialog;

sub clicker {
  
  # get the ids of the selected items
  my @stuff = $lv->get_selected();
  
  # get the hashrefs of the selected items
  my @dat = $lv->get_data();

  if (defined $stuff[0]) {
    print "These IDs were selected: " . join(',',@stuff) . "\nfirst selected item:\n";
    foreach (keys %{$dat[0]}) {
      print "\t$_\t$dat[0]->{$_}\n";
    }
  }
  else {
    print "No Selection\n";
  }
}

sub win_Terminate {
  -1
}

