#!/usr/bin/perl -w

use Test;
use strict;

BEGIN
  {
  unshift @INC, '../..';
  plan tests => 23;
  }

use CoW::Bunch;

my $one = new CoW::Bunch ( x => 1, y => 2, z => 3, name => 'one thing' );
my $two = new CoW::Bunch ( x => 3, y => 4, z => 5, name => 'another',);
my $three = new CoW::Bunch ( x => 3, y => 4, z => 5, name => 'another',);
my $four = new CoW::Bunch ( x => 6, y => 7, z => 8, name => 'foo',);
my $five = new CoW::Bunch ( x => 6, y => 7, z => 8, name => 'five',);

my $thing = new CoW::Bunch ( x => 9, y => 8, z => 7,
  contains => [ $one, $two ], );

# check item count (recursive or not)
ok ($thing->items(0),2);
ok ($thing->items(1),2);
$one->insert($five);
ok ($thing->items(0),3); # recursive must be one more
ok ($thing->items(1),2);
$one->delete($five);     # restore simple bunch for next tests

# check wether insert/delete do
ok ( scalar $thing->insert($three), 1);
ok ($thing->items(),3);

# dont insert twice
ok ( scalar $thing->insert($three), 0);
ok ($thing->items(),3);

$thing->delete($one);
ok ($thing->items(),2);

# dont delete twice
$thing->delete($one);
ok ($thing->items(),2);

# dont insert yourself into yourself
$thing->insert($thing);
ok ($thing->items(),2);

my @list = $thing->insert($one,$four);
ok (scalar @list, 2);
ok ($list[0], $one);
ok ($list[1], $four);
ok ($thing->items(),4);

# check by_field
$one->insert( CoW::Bunch->new ( name => 'some other' ));
ok (scalar $thing->by_field('name','other'),3);
ok (scalar $thing->by_field('name','other',1),2);

# check contains()
ok ( scalar $thing->contains($two,$three),2);

# check wether insert makes copy of objects that belong to someone else
my $another = new CoW::Bunch ( contains => [ $one, $two ] );
if ("$another->{_things}->[0]" ne "$one")
  {
  ok (1,1);
  }
else
  {
  ok ("$another->{_things}->[0]","should not equal $one");
  }
# check wether insert leaves the original alone and inserts the copy
my $p1 = $one->{_parent};
$another = new CoW::Bunch ( contains => [ $one, $two ], name => "another one" );
ok ($p1,$one->{_parent});

# check empty()
$another->empty();
ok ($another->items(),0);

# check traverse
my $bunch = 0;
my $general = 0;
my $x = 5; my $y = 6;

$one = new CoW::Bunch ( x => 1, y => 2, z => 3, name => 'one thing' );
$two = new CoW::Bunch ( x => 3, y => 4, z => 5, name => 'another',);
$another = new CoW::Bunch ( contains => [ $one, $two ] );
$another->traverse ( { callback => \&general, 'CoW::Bunch' => \&bunch }, 0,
  $x,$y,7);

ok ($bunch,($x+$y+7)*3);
ok ($general,($x+$y+7)*3);

sub bunch 
  {
  my ($self,$x,$y,$z) = @_; 
  $bunch += $x+$y+$z; 
  # print "bunch $self $x $y $z\n"; 
  }

sub general 
  {
  my ($self,$x,$y,$z) = @_; 
  $general += $x+$y+$z; 
  # print "gen $self $x $y $z\n";
  }
