#!perl
use Cassandane::Tiny;

sub test_references_star ($self)
{
    xlog $self, "test THREAD with a star configuration of inter-message references";
    xlog $self, "and apparently similar subjects";
    my $talk = $self->{store}->get_client();
    my $res;

    xlog $self, "append some messages";
    my %exp;
    my %exp_by_sub;
    my $N = 20;
    my @subjects = ( 'cosby sweater', 'brooklyn', 'portland' );
    foreach my $uid (1..$N)
    {
        my $sub = $subjects[($uid - 1) % scalar(@subjects)];
        $exp_by_sub{$sub} ||= [];
        my $msg;
        if (scalar @{$exp_by_sub{$sub}})
        {
            my $parent = $exp_by_sub{$sub}->[0];
            $msg = $self->make_message("Re: " . $parent->subject,
                                       references => [ $parent ]);
        }
        else
        {
            $msg = $self->make_message($sub);
        }
        push(@{$exp_by_sub{$sub}}, $msg);
        $exp{$uid} = $msg;
    }
    xlog $self, "check the messages got there";
    $self->check_messages(\%exp, keyed_on => 'uid');

    my @expthreads;
    foreach my $sub (@subjects)
    {
        my @thread = ( map { $_->uid } @{$exp_by_sub{$sub}} );
        my $parent = shift(@thread);
        push(@expthreads, [ $parent, map { [ $_ ] } @thread ] );
    }

    xlog $self, "The REFERENCES algorithm gives the true thread structure which is flat";
    $res = $talk->thread('REFERENCES', 'US-ASCII', 'ALL');
    $self->assert_deep_equals(\@expthreads, $res);

    xlog $self, "The ORDEREDSUBJECT algorithm gives the same flat view";
    $res = $talk->thread('ORDEREDSUBJECT', 'US-ASCII', 'ALL');
    $self->assert_deep_equals(\@expthreads, $res);

    xlog $self, "Double-check the messages are still there";
    $self->check_messages(\%exp, keyed_on => 'uid');
}
